是否可以在同一属性上使用公共 init 访问器和私有 setter?
目前我收到错误CS1007 “已定义属性访问器”。
public record Stuff
{
public int MyProperty { get; init; private set; } // Error
public void SetMyProperty(int value) => MyProperty = value;
}
var stuff = new Stuff
{
MyProperty = 3, // Using the init accessor
};
stuff.SetMyProperty(4); // Using the private setter (indirectly)
Run Code Online (Sandbox Code Playgroud)
我最好的猜测是使用私有成员变量,该变量的属性get和init访问器(不是自动实现的)和 setter 成员函数。可以更轻松地完成吗?
你不能。添加 init 关键字是为了尝试使对象具有不可变属性。
所以如果你有记录:
public record Stuff
{
public int MyProperty { get; init; } // This can not be changed after initialization
}
Run Code Online (Sandbox Code Playgroud)
MyProperty只能在记录初始化期间设置。
如果您希望您的属性是可变的,那么您可以使用set访问器而不是init.
public record Stuff
{
public int MyProperty { get; set; } // This can
}
Run Code Online (Sandbox Code Playgroud)
类似于指定构造函数来初始化您的值,您可以使用私有支持字段,以便您仍然可以利用初始化逻辑并允许在没有特定构造函数的情况下进行初始化
public record Stuff
{
private int _myProperty;
public int MyProperty { get => _myProperty; init => _myProperty = value; }
public void SetMyProperty(int value) => _myProperty = value;
}
var stuff = new Stuff
{
MyProperty = 3 // Using the init accessor
};
stuff.SetMyProperty(4); // Using the private setter (indirectly)
Run Code Online (Sandbox Code Playgroud)