且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Windows窗体中调用类函数?

更新时间:2023-12-06 14:53:22

对于您显示的方法,为了调用它,您需要一个包含类的实例:该方法所属的类的示例,使用 new 关键字在某些时候创建:

In the case of the method you show, in order to call it you need an instance of the containing class: an example of the class that the method is part of, created at some point with the new keyword:
MyClass mc = new MyClass();
...
mc.dbConnection();



如果将其更改为 static 方法:


If you change it to a static method:

public static void dbConnection(string ProjectName112)
{
  string strProject = ProjectName112; //Enter your SQL server instance name
}

然后你不需要实例,你可以只使用类名:

Then you don;t need the instance, you can just use the class name:

MyClass.dbConnection();

但是方法可以' t访问MyClass类的任何非静态字段,属性或方法。



但是......你展示的例子没有任何用处:它没有返回值,并且当方法退出时,字符串变量 strProject 被销毁,因此nothign将影响外部世界。



我认为你需要仔细考虑一下你在这里想要达到的目标:这可能不会起作用......

But then the method can't access any non-static field, properties or methods of the MyClass class.

But...the example you show does nothing useful: it returns no value, and the string variable strProject is destroyed when the method exits, so nothign will influence the outside world.

I think you need to think a bit about exactly what you are trying to achieve here: this probably isn't going to work...