简体   繁体   中英

Auto-Property Initializers not filled

I have a class with two properties one filled with the new auto-property initializer of c# 6.0 and one implementing only the getter shorthand:

public SampleEnum SampleProp1 { get; } = SampleEnum.Value1;
public SampleEnum SampleProp2 { get { return SampleEnum.Value1; } }

this class is a parameter of an wcf endpoint, when this endpoint is called the SampleProp1 contains only the default enum value.

Why is this happening?

The auto-property initializer in C# 6.0 is syntactic sugar and the compiler will create a backing field for the property that is initialized to the given expression.

Therefore, your code is equivalent to the following declaration (I added a class ´SampleClass` for clarification):

class SampleClass
{
    // compiler-generated backing field initialized by the field initializer
    private readonly SampleEnum __sampleProp1 = SampleEnum.Value1;

    public SampleEnum SampleProp1 { get { return __sampleProp1; } }

    public SampleEnum SampleProp2 { get { return SampleEnum.Value1; } }
}

Your problem comes from the fact that the deserializer used by WCF does not execute the field initializers .

A possible solution would be to make use of the OnDeserializing or OnDerserialized attributes and place all your initialization code into a separate method (as described in this question: Field Initializer in C# Class not Run when Deserializing ).

Is SampleEnum really an enum? I tried your code in a simple class with an actual enum and it seemed to work fine.

I can see where there might be a problem of SampleEnum was actually a class though, and Value1 had not yet been initialized when the class with the properties was initialized.

Here's what I tried that works as expected:

class Program
{
    static void Main(string[] args)
    {
        var x = new MyClass();
        Debug.Print("{0}", x.SampleProp1);
        Debug.Print("{0}", x.SampleProp2);
    }
    public class MyClass
    {
        public enum SampleEnum { Value0, Value1 , Value2 };
        public SampleEnum SampleProp1 { get; } = SampleEnum.Value1;
        public SampleEnum SampleProp2 { get { return SampleEnum.Value1; } }
    }
}

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