Set properties of a class only through constructor

前端 未结 5 1984
野趣味
野趣味 2021-01-01 11:39

I am trying to make the properties of class which can only be set through the constructor of the same class.

5条回答
  •  生来不讨喜
    2021-01-01 12:07

    With C# 9 it introduces 'init' keyword which is a variation of 'set', which is the best way to do this.

    The one big limitation today is that the properties have to be mutable for object initializers to work: They function by first calling the object’s constructor (the default, parameterless one in this case) and then assigning to the property setters.

    Init-only properties fix that! They introduce an init accessor that is a variant of the set accessor which can only be called during object initialization:

    public class Person
    {
        public string FirstName { get; init; }
        public string LastName { get; init; }
    }
    

    Ref: https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/

提交回复
热议问题