如果您想使单个属性不可变,那么仅初始化(init-only)属性是极好的。如果您想要整个对象是不可变的,行为像一个值,那么你应该考虑声明它为一个记录(record):
public record Person { public string FirstName { get; init; } public string LastName { get; init; } }
如果想要复制只读对象,然后改变某个值,则要用with
Person person = new() { FirstName = "11", LastName = "22" }; var othP = person with { FirstName = "22" };