小编Ton*_*cki的帖子

是否可以在运行时设置 C# init-only 属性?

我尝试编写一些 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; }
    }

}
Run Code Online (Sandbox Code Playgroud)

运行时示例。

PS D:\Users\Tony> ($Person = New-Person)

Name
----
Jane Dough

PS D:\Users\Tony> $Person.Name = "John Smith"
PS D:\Users\Tony> $Person

Name
----
John Smith

PS D:\Users\Tony> …
Run Code Online (Sandbox Code Playgroud)

c# properties init-only

5
推荐指数
1
解决办法
60
查看次数

标签 统计

c# ×1

init-only ×1

properties ×1