类 中是否应该在内部使用属性或字段?

Should properties or fields be used internally in classes?

通常,您希望通过为内部状态提供 getter 和 setter 来封装数据。示例:

public class Person {
    private int age;
    public int Age { 
        get { return age; }
        set { age = value; }
    }
}

void Main() {
    Person alice = new Person();
    alice.Age = 20;
}

但是假设我们发生了这种情况:

public class Person {
    private int age;
    public int Age { 
        get { return age; }
        set { age = value; }
    }

    public String WhatIsMyAge() {
        return "My age is: " + ???;
    }
}

void Main() {
    Person alice = new Person();
    alice.Age = 20;

    Console.WriteLine(alice.WhatIsMyAge());
}

在这里使用 属性 或字段更好吗?有关系吗?既然我们在原生内部class,我们还关心封装内部吗?

如果您使用的是没有任何额外功能的简单属性,那没关系。 但是,在这种情况下,您为什么不选择使用 Auto-implemented properties ?

如果您的 属性 getter 或 setter 包含额外的功能,那么您是否直接使用 属性 访问器或支持字段并不重要。这完全取决于所需的行为。

始终使用 属性、尤其是 class 代码中的 。我会说:不小心在 class 代码错误中使用了 属性 的支持字段。

为了不意外使用支持字段,应该付出很多努力:

  • 如果您使用自动实现属性,则没有您可能会意外使用的支持字段名称。 (当然有一个,但它没有名字;所以不小心使用它是不可能的)。
  • 如果自动实现属性不够(不再),我总是在支持字段中附加下划线。 age 和 Age 更容易混淆 _Age 和 Age。
  • 有些人超越了这一点。就像使用 Dictionary<string, object> 作为每个 class 的支持字段一样。使用 "CallerMemberName" 和 simialr 语法糖,找出用作索引的 属性 名称可能很简单。

在你的例子中:

private int age;
public int Age { 
    get { return age; }
    set { age = value; }
}

你应该使用 auto-implemented properties anyway

但是如果你有一个支持字段在 属性 的 getter 或 setters 中提供额外的逻辑,比如验证,一定要使用 属性 而不是支持字段:这使得类型无法将值分配给通过 属性 的 setter.

分配时无法通过验证的属性

读取 支持字段应该是安全的,因为。但为了保持一致性,通过 属性.

执行读取和写入操作