所以我听说验证属性中的值是这样的:
//dummy example, let's assume that I want my value without dots
public string MyProp
{
set
{
if(value.Contains('.'))
throw new ArgumentException("Must not contain '.'", "value");
}
}
是错误的,我应该避免它。
但在早些时候我被告知这是好方法。我们可以使用封装,只有一个地方可以检查、DRY 等。
我的小例子有什么问题吗?
最佳答案
在属性 setter 中抛出异常并没有错。但是您应该抛出一个 ArgumentException
,并且还实际设置该属性的值!
private string _myprop;
public string MyProp{
set{
if(value.Contains('.')) throw new ArgumentException("Must not contain .");
this._myprop=value;
}
get { return this._myprop; }
}
来自 article on best practices in MSDN :
Property getters should be simple operations without any preconditions. If a getter might throw an exception, consider redesigning the property to be a method. This recommendation does not apply to indexers. Indexers can throw exceptions because of invalid arguments.
It is valid and acceptable to throw exceptions from a property setter.
关于c# - 验证属性中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15885290/