C#9中的Init-Only和ReadOnly有什么区别? [英] What is difference between Init-Only and ReadOnly in C# 9?

查看:212
本文介绍了C#9中的Init-Only和ReadOnly有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 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.

推荐答案

如新C#9中所述

今天的一大限制是属性必须是可变的 为了使对象初始值设定项起作用:它们通过先调用 对象的构造函数(在这种情况下,默认为无参数的构造函数), 然后分配给属性设置器.

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.

但是,通过仅Init属性,您可以使用对象初始化程序.

However, with Init-only properties you can use object initializers.

这篇关于C#9中的Init-Only和ReadOnly有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆