C#无法在静态上下文中访问非静态成员字段,除非实际处于静态上下文中 [英] C# Cannot access non-static member field in static context, without actually being in static context
问题描述
谁能解释为什么我得到错误
即使我不在静态上下文中,也无法在静态上下文中访问非静态字段wtf。
Can anyone explain why I get the error "Cannot access non-static field wtf in static context, even though I am NOT in a static context.
我在 public int variable = wtf.queuePosition;行上收到错误消息。
I get the error on the line "public int variable = wtf.queuePosition;"
class Test
{
public Test wtf = new Test();
public int variable = wtf.queuePosition;
private int queuePosition;
public Test()
{
queuePosition = 5;
}
}
推荐答案
尽管我不是在静态环境中。
though I am NOT in a static context.
实例成员变量的初始化是在构造函数的代码执行之前完成的,此时,仍然没有 this
引用。
The initialization of instance member variables is done before the code of your constructor is executed. At this time, there is still no this
reference.
所以我怕您错了。从编译器的角度来看,您是处于静态上下文中。
So I'm afraid your wrong. From the point of view of the compiler, you are in a static context.
实例字段的变量初始化程序无法引用正在创建的实例。因此,在变量初始值设定项中引用
this是编译时错误,因为对于变量初始值设定项通过简单名称引用任何实例成员都是编译时错误。
A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name.
这篇关于C#无法在静态上下文中访问非静态成员字段,除非实际处于静态上下文中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!