c# - 验证属性中的值

标签 c# dry encapsulation

所以我听说验证属性中的值是这样的:

//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/

相关文章:

clojure - 如何封装在clojure中?

c# - 如何将数据从 DataSet 放入列表

c# - 在两个模型之间创建 ManyToMany 关系

java - 微服务共享对象

ruby-on-rails - Rails View DRYness - 你是在 View 中设置变量还是只创建干净的方法?

objective-c - 在通用应用程序上分离 iPhone 和 iPad 类有什么好处吗?

java - 封装的指标是什么?

c# - 在 C# 中异步加载 BitmapImage

c# - sc.exe 将 exe 安装为服务?

java - 返回数据结构以显示信息