是否可以在运行时设置C#init-only属性?
c#
我尝试编写一些 C# 代码来创建一个 init-only 属性。我惊讶地发现该属性可以在运行时更改。我是否误解了不变性的概念?我正在使用 Visual Studio 社区 16.9.3。
示例代码。
namespace TonyStachnicki.Windows {
using System.Management.Automation;
[Cmdlet(VerbsCommon.New, "Person")]
public class NewPerson : Cmdlet {
protected override void ProcessRecord() {
var _Person = new Person {
Name = "Jane Dough"
};
WriteObject(_Person);
}
}
public class Person {
public string Name { get; init; }
}
}
运行时示例。
PS D:UsersTony> ($Person = New-Person)
Name
----
Jane Dough
PS D:UsersTony> $Person.Name = "John Smith"
PS D:UsersTony> $Person
Name
----
John Smith
PS D:UsersTony> $Person.Name = "Jane Jones"
PS D:UsersTony> $Person
Name
----
Jane Jones
PS D:UsersTony>
该程序的行为与此 Person 类相同。
public class Person {
public string Name {
get { return m_Name; }
init { m_Name = value; }
}
private readonly string m_Name;
}
在这种情况下,只读修饰符也被忽略。
我想大多数人都会对 init-only 特性的效果感到惊讶。