我有一个这样的对象:
(我也有私有(private)字段,但为了简化示例而将其删除)
public MyObject
{
public int prop1 {get(); set()}
public string prop2 {get(); set()}
public bool prop3 {get(); set()}
public bool enabled {get(); private set();}
public void enable()
{
this.enabled = true;
}
public void disable()
{
this.enabled = false;
}
}
我的对象是审计分析的结果,当它发送给客户端时不能再编辑所以我想防止在“启用”属性为 false 时对 prop1-2-3 进行更改所以我添加了这个方法:
private T setProperty<T>(T value)
{
if (this.enabled == true)
{
return value:
}
else
{
throw new Exception();
}
}
并以这种方式编辑属性:
public int prop1
{
get{};
set
{
// see how we can call a method below? or any code for that matter..
prop1 = setProperty<int>(value);
}
}
是一个好的解决方案还是有更好的方法? 我可以在“设置”方法中返回什么类型的异常?
请您参考如下方法:
目前,您的属性是递归的并且会爆炸 - 如果 JIT 决定尾调用它,则可能会出现堆栈溢出或无限循环。
除此之外,方法肯定会奏效。就我个人而言,我会使用 InvalidOperationException,也许还有一条消息提到 enabled 标志。另外,为了方便起见,我可能会这样做:
private int prop1;
public int Prop1 {
get { return prop1; }
set { SetValue(ref prop1, value); }
}
private string prop2;
public string Prop2 {
get { return prop2; }
set { SetValue(ref prop2, value); }
}
private bool prop3;
public bool Prop3 {
get { return prop3; }
set { SetValue(ref prop3, value); }
}
void SetValue<T>(ref T field, T value) {
if(!Enabled) {
throw new InvalidOperationException(
"The property cannot be changed because the Enabled flag is not set");
}
field = value;
}
public bool Enabled {get;private set;}
