问题
I am going through C# 9 new features which will be released soon. Init-Only properties are being introduced with it.
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; }
}
With this declaration, the client code above is still legal, but any subsequent assignment to the FirstName and LastName properties is an error. What does this line mean? If ReadOnly also does the same thing then what is use of Init-Only property.
回答1:
As stated in the new C# 9 features post,
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.
However, value types with readonly modifiers are immutable as stated in readonly documentation.
Therefore, it is not possible to use readonly properties with object initializers.
However, with Init-only properties you can use object initializers.
来源:https://stackoverflow.com/questions/62372422/what-is-difference-between-init-only-and-readonly-in-c-sharp-9