简体   繁体   中英

Property Initializer cannot reference non-static field

I thought the new C# 6.0 property initializers like this.

public MyType MyProperty { get; } = new MyType(OtherProperty);

was the equivalent of this

private MyType _myVariable;
public MyType MyProperty { get { return _myVariable ?? _myVariable = new MyType(OtherProperty); } }

(that OtherProperty is available as part of the instance, not limited to being static)

But in the above first I get "field initializers cannot reference non-static field". Am I doing it wrong, or are property initializers just as limited as

public readonly MyType MyVariable = new MyType(NeedsStaticReference);

In your second example the field is set on first use.

The problem here, is the field intializer is set immediately before the constructor, and there is no guarantee the other property is set or constructed or what order this happens.

If you want to assign something on construction you will need to do it in the constructor

Fields (C# Programming Guide)

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration.

A field initializer cannot refer to other instance fields .

And some more information

A field can optionally be declared static. This makes the field available to callers at any time, even if no instance of the class exists. For more information, see Static Classes and Static Class Members.

A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. A static``readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run tim

It's, actually, like this:

private readonly MyType _myVariable = new MyType(OtherProperty);
public MyType MyProperty { get { return _myVariable; } }

Thus, the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM