[英]public vs public static Methods
Having read the access modifiers in C# progamming tutorial, I come to conclusion that defining a method public
is enough for it to be "seen" from another Form
of the same namespace. 在C#编程教程中阅读了访问修饰符后,我得出结论,定义一个方法
public
足以让它从同一命名空间的另一个Form
中“看到”。
However, in practise whenever I tried to implement this, I also had to define the method as static
in order for it to be referenced from other Forms
of the same namespace. 但是,在实践中,每当我尝试实现它时,我还必须将方法定义为
static
,以便从同一名称空间的其他Forms
引用它。
Am I loosing something? 我失去了什么吗? I am doing somethning wrong?
我做错了什么?
For a public static
method, you don't need a reference to an object. 对于
public static
方法,您不需要对对象的引用。 The method is static and can be accessed on class
level. 该方法是静态的,可以在
class
级别访问。
If you can't access a public method, then you need a reference to the object, then you can. 如果您无法访问公共方法,那么您需要对该对象的引用,然后您可以。
public class AClass
{
public void DoSomething() {}
public static void DoSomethingElse() {}
}
You can use them as follows: 您可以按如下方式使用它们:
AClass.DoSomethingElse(); // no object reference required
AClass.DoSomething(); // will give compiler error, since you have no object reference.
var anObject = new AClass();
anObject.DoSomething(); // will work fine.
anObject.DoSomethingElse(); // compile error (thx hvd).
public static
method do not need object instance, they can be used without creating any instance of the class public static
方法不需要对象实例,可以在不创建任何类实例的情况下使用它们
ClassName.MyStaticPublicMethodName()
where as public
(non-static) method require an Instance of the Class, public (non-static) method in general helps you to work with the data member (field) of the object. 在
public
(非静态)方法需要类的实例的情况下,公共(非静态)方法通常可以帮助您使用对象的数据成员(字段)。
To use a non-static public method you need to create instance of the class 要使用非静态公共方法,您需要创建类的实例
ClassName obj = new ClassName();
obj.MyPublicMethod();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.