属性永远不为null#

属性永远不为null#,第1张

概述在重构代码时,我想出了如下的实例 private string _property = string.Empty;public string Property{ set { _property = value ?? string.Empty); }} 稍后在一个方法中我看到以下内容: if (_property != null){ //...} 假设_property仅由 在重构代码时,我想出了如下的实例

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; }}

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

总结

以上是内存溢出为你收集整理的属性永远不为null#全部内容,希望文章能够帮你解决属性永远不为null#所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1216958.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存