Why is it necessary to call :this() on a struct to use automatic properties in c#?

后端 未结 2 589
情书的邮戳
情书的邮戳 2021-02-03 17:05

If I define a struct in C# using automatic properties like this:

public struct Address
{
    public Address(string line1, string line2, string city, string state         


        
2条回答
  •  不知归路
    2021-02-03 18:05

    Note: as of C# 6, this isn't required - but you should be using read-only automatically-implemented properties with C# 6 anyway...

    this() makes sure that the fields are definitely assigned as far as the compiler is concerned - it sets all fields to their default values. You have to have a fully constructed struct before you can start accessing any properties.

    It's annoying, but that's the way it is. Are you sure you really want this to be a struct though? And why use a protected setter on a struct (which can't be derived from)?

提交回复
热议问题