我在 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)
init 关键字创建所谓的 Init Only Setter。他们将 init only 属性和索引器的概念添加到 C#。这些属性和索引器可以在对象创建时设置,但只有在对象创建完成后才能有效地获取。
引入的主要原因是避免样板代码。
像 Point 这样简单的不可变对象需要:
struct Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
}
Run Code Online (Sandbox Code Playgroud)
init 访问器允许调用者在构造过程中改变成员,从而使不可变对象更加灵活。这意味着对象的不可变属性可以参与对象初始值设定项,因此不需要类型中的所有构造函数样板。Point 类型现在很简单:
struct Point
{
public int X { get; init; }
public int Y { get; init; }
}
Run Code Online (Sandbox Code Playgroud)
然后消费者可以使用对象初始值设定项来创建对象
var p = new Point() { X = 42, Y = 13 };
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读包含更多详细信息和说明的提案:
https://github.com/dotnet/csharplang/blob/c2df2ee72f4b36fca2e07c701a90a0dba8d1fc20/proposals/init.md