Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

c# - How can I set the value of auto property backing fields in a struct constructor?

Given a struct like this:

public struct SomeStruct
{
    public SomeStruct(String stringProperty, Int32 intProperty)
    {
        this.StringProperty = stringProperty;
        this.IntProperty = intProperty;
    }

    public String StringProperty { get; set; }
    public Int32 IntProperty { get; set; }
}

Of course, a compiler error is generated that reads The 'this' object cannot be used before all of its fields are assigned to.

Is there a way to assign values to the backing fields or the properties themselves, or do I have to implement properties the old-fashioned way with my own explicit backing fields?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Prior to C# 6, you need to use the "this" constructor in this scenario:

public SomeStruct(String stringProperty, Int32 intProperty) : this()
{
    this.StringProperty = stringProperty;
    this.IntProperty = intProperty;
}

Doing this calls the default constructor and by doing so, it initializes all the fields, thus allowing this to be referenced in the custom constructor.


Edit: until C# 6, when this started being legal; however, these days it would be much better as a readonly struct:

public readonly struct SomeStruct
{
    public SomeStruct(string stringProperty, int intProperty)
    {
        this.StringProperty = stringProperty;
        this.IntProperty = intProperty;
    }

    public string StringProperty { get; }
    public int IntProperty { get; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...