为什么我只能从静态函数访问静态成员? [英] Why can I only access static members from a static function?
问题描述
我有一个类的静态函数。
I have a static function in a class.
每当我尝试使用非静态数据成员,我获得以下编译错误。
whenever I try to use non static data member, I get following compile error.
这是对象引用是必需的非静态字段,方法或属性成员
An object reference is required for the nonstatic field, method, or property member
为什么表现成这样?
推荐答案
一个非静态成员属于一个实例。这是毫无意义的解决不知何故,你是在谈论一个类的实例。在静态情况下,你没有一个实例,这就是为什么你不能没有明确提到对象引用访问非静态成员。
A non-static member belongs to an instance. It's meaningless without somehow resolving which instance of a class you are talking about. In a static context, you don't have an instance, that's why you can't access a non-static member without explicitly mentioning an object reference.
其实,您可以通过明确指定对象引用访问非静态成员在静态方面:
In fact, you can access a non-static member in a static context by specifying the object reference explicitly:
class HelloWorld {
int i;
public HelloWorld(int i) { this.i = i; }
public static void Print(HelloWorld instance) {
Console.WriteLine(instance.i);
}
}
var test = new HelloWorld(1);
var test2 = new HelloWorld(2);
HelloWorld.Print(test);
如果没有明确提到该实例中的打印
方法,如何将它知道它应该打印1和2不?
Without explicitly referring to the instance in the Print
method, how would it know it should print 1 and not 2?
这篇关于为什么我只能从静态函数访问静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!