C#9中的Init-Only和ReadOnly有什么区别? [英] What is difference between Init-Only and ReadOnly in C# 9?
问题描述
我正在通过 C#9新功能即将发布. 仅限Init 属性是被引入.
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访问器,它是set访问器的变体,只能在对象初始化期间调用它:
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; }
}
使用此声明,上面的客户端代码仍然合法,但是随后对FirstName和LastName属性的任何分配都是错误的.这行是什么意思?如果ReadOnly也做同样的事情,那么Init-Only属性的用途是什么.
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.