我一直在阅读 C#9 中的 init-only 属性,但我认为我们已经有了只能在构造函数中设置的只读属性。在那之后,它是不可变的。
例如,在这里的类中,Name
和Description
都可以在构造函数中赋值,但只能在构造函数中赋值,这正是 init-only 属性的描述方式。
class Thingy {
public Thingy(string name, string description){
Name = name;
Description = description;
}
public string Name { get; }
public string Description { get; }
public override string ToString()
=> $"{Name}: {Description}";
}
Run Code Online (Sandbox Code Playgroud)
using System;
class Program {
public static void Main (string[] args) {
var thingy = new Thingy("Test", "This is a test object");
Console.WriteLine(thingy);
// thingy.Name = “Illegal”; <— Won’t compile this …
Run Code Online (Sandbox Code Playgroud) 我在 C# 9 预览版中遇到了c# 中的“ init ”关键字。它是什么意思,它的应用是什么?
public class Person
{
private readonly string firstName;
private readonly string lastName;
public string FirstName
{
get => firstName;
init => firstName = (value ?? throw new ArgumentNullException(nameof(FirstName)));
}
public string LastName
{
get => lastName;
init => lastName = (value ?? throw new ArgumentNullException(nameof(LastName)));
}
}
Run Code Online (Sandbox Code Playgroud) 我正在浏览即将发布的C# 9 新功能。Init-Only属性正在被引入。
今天的一大限制是属性必须是可变的,对象初始值设定项才能工作:它们通过首先调用对象的构造函数(在本例中为默认的无参数构造函数)然后分配给属性设置器来起作用。
仅初始化属性解决了这个问题!他们引入了一个 init 访问器,它是 set 访问器的变体,只能在对象初始化期间调用:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
Run Code Online (Sandbox Code Playgroud)
有了这个声明,上面的客户端代码仍然是合法的,但是对 FirstName 和 LastName 属性的任何后续分配都是错误的。这条线是什么意思?如果 ReadOnly 也做同样的事情,那么 Init-Only 属性的用途是什么。