什么是"静态方法"在C#中?
问题描述:
当您添加static关键字的方法是什么意思?
What does it mean when you add the static keyword to a method?
public static void doSomething(){
//Well, do something!
}
你能添加静态
关键字来上课?会是什么话呢?
Can you add the static
keyword to class? What would it mean then?
答
A 静态
功能,不同于一般的(实例的)功能,是不与类的实例相关联。
A static
function, unlike a regular (instance) function, is not associated with an instance of the class.
A 静态
类是只能包含静态
成员,因此不能被实例化的类。
A static
class is a class which can only contain static
members, and therefore cannot be instantiated.
例如:
class SomeClass {
public int InstanceMethod() { return 1; }
public static int StaticMethod() { return 42; }
}
为了调用 InstanceMethod
,你需要的类的实例:
In order to call InstanceMethod
, you need an instance of the class:
SomeClass instance = new SomeClass();
instance.InstanceMethod(); //Fine
instance.StaticMethod(); //Won't compile
SomeClass.InstanceMethod(); //Won't compile
SomeClass.StaticMethod(); //Fine