C# Cannot access non-static member field in static

2020-02-07 06:59发布

问题:

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.

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;
    }
}

回答1:

though I am NOT in a static context.

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.

From the C# specification (17.4.5.2 Instance field initialization):

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.



回答2:

You are assigning the variable to the value of a property within another variable. Your variable wtf is the non-static, however the variable assignment within a class is static. So the assignment, 'public int variable = wtf.queuePosition;', is within a static context.

One obvious reason this is not allowed is shown within your example. Your code would have a stack overflow exception real quickly. As each instance of Test is newing up another instance of Test, which will new up another ...



标签: c# static