对于差异的快速示例:
class C
{
public int Prop1 { get; } = 2;
public int Prop2 { get; init; } = 4;
// constructor
public C()
{
// Prop1 is only assignable here
Prop1 = 6;
// Prop2 is assignable here, but also in the "object initializer"
Prop2 = 8;
}
}
// the stuff inside the {} is what the docs are referring to
// as "object initializer"
var c = new C()
{
// this next line would be an error
// Prop1 = 10,
// setting Prop2 works fine,
// this also overwrites what was set in the constructor
Prop2 = 10
}
Prop2
不能在这些{}结束后再次设置,这就是区别
init
从…起
set
。