c# - 属性永远不会为 null c#

标签 c# reflection properties refactoring

在重构代码时,我想到了如下实例

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

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

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

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

也就是说,有什么方法可以通过反射魔法或其他方法使 _property 永远为 null?

最佳答案

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

没错,就是多余的。这就是 Properties 的实际用途。我们不应该直接访问类的字段。我们应该使用属性访问它们。所以在相应的 setter 中,我们可以嵌入任何逻辑,我们可以放心,每次我们尝试设置一个值时,这个逻辑都会被再次验证。这个论点甚至适用于类的方法。在方法中,我们必须使用属性而不是实际字段。此外,当我们想要读取一个字段的值时,我们应该使用相应的getter。

一般来说,属性增强了封装的概念,封装是面向对象编程 OOP 的支柱之一。

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

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

我们已经声明了一个代表客户的类。客户对象应具有三个属性:IdFirstNameLastName

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

答案还是一样的,它们提供了一种封装机制。但是让我们考虑一下从长远来看这对我们有什么帮助。假设有一天有人决定客户的名字应该是一个长度小于 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; }
}

考虑上述两种方法,但必须重新访问所有代码库并进行此检查。很明显,属性获胜。

关于c# - 属性永远不会为 null c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33816075/

相关文章:

c# - 如何重新设计 ReSharper 8 生成的代码的样式

c# - 有没有办法得到 typeof Func<T, bool>?

javascript - propertyIsEnumerable(x) 与 x in

swift - 无法修改 Codable 类属性?

java - 如何使用 Class 的实例作为泛型类型?

java - 在Java中: How to access static property of dynamically referenced class?

c# - 仅在一个类中设置泛型类型

c# - UWP 标题栏按钮设置为透明时呈白色

c# - Json.Net 将复杂对象序列化为 Xml 属性和值

java - 是否可以重新初始化类中的静态可变字段?