加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

属性永远不为null#

发布时间:2020-12-16 10:00:08 所属栏目:百科 来源:网络整理
导读:在重构代码时,我想出了如下的实例 private string _property = string.Empty;public string Property{ set { _property = value ?? string.Empty); }} 稍后在一个方法中我看到以下内容: if (_property != null){ //...} 假设_property仅由Property的setter
在重构代码时,我想出了如下的实例

private string _property = string.Empty;
public string Property
{
    set { _property = value ?? string.Empty); }
}

稍后在一个方法中我看到以下内容:

if (_property != null)
{
    //...
}

假设_property仅由Property的setter设置,这个代码是多余的吗?

我有没有办法,通过反射魔法或其他方法_property可以为空?

解决方法

Assuming that _property is only set by the setter of Property,is this
code redundant?

确实,这是多余的.这是Properties的实际目的.我们不应该直接访问类的字段.我们应该使用Property访问它们.所以在相应的setter中,我们可以嵌入任何逻辑,我们可以保证每次我们尝试设置一个值时,这个逻辑将再次被验证.这个参数甚至适用于类的方法.在方法中,我们必须使用属性而不是实际字段.此外,当我们想要读取字段的值时,我们应该使用相应的getter.

通常,属性增强了封装的概念,封装是面向对象编程OOP的支柱之一.

很多时候,当我们想要设置一个值时,没有任何逻辑应该应用.以下面的例子为例:

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我们已经宣布了一个代表客户的类. Customer对象应具有三个属性:Id,FirstName和LastName.

一个直接的问题,当有人读这个类时,为什么有人会在这里使用属性?

答案是同样的,它们提供了封装机制.但是让我们考虑一下从长远来看这对我们有什么帮助.假设有一天有人决定客户的名字应该是长度小于20的字符串.如果上面的类声明如下:

public class Customer
{
    public int Id;
    public string FirstName;
    public string LastName;
}

那么我们应该在我们创建的每个实例中检查FirstName的长度!否则,如果我们选择了属性声明,我们可以轻松地使用Data Annotations

public class Customer
{
    public int Id { get; set; }
    [StringLength(20)]
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

就是这样.另一种方法可能如下:

public class Customer
{
    public int Id { get; set; }
    private string firstName;
    public string FirstName 
    { 
        get { return firstName }
        set
        {
            if(value!=null && value.length<20)
            {
                firstName = value;
            }
            else
            {
                throw new ArgumentException("The first name must have at maxium 20 characters","value");
            }
        } 
    }
    public string LastName { get; set; }
}

考虑上述两种方法,必须重新访问所有代码库并进行此检查.很明显,物业赢了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读