可能存在重复问题:
What is the difference between a field and a property in C#
Should I use public properties and private fields or public fields for data?
以下两者之间有何区别:
public string varA;
和
public string varA { get; set; }
可能存在重复问题:
What is the difference between a field and a property in C#
Should I use public properties and private fields or public fields for data?
以下两者之间有何区别:
public string varA;
和
public string varA { get; set; }
公共属性访问器在未来能让你更加灵活。
如果你想为设置属性值添加验证,只需要编写非默认的setter。这不会影响其他代码。
另外,有时候你可能需要用代码替换默认的getter。对于公共变量来说,这可能会很麻烦。
public int Item { get; private set; } // read-only outside the class. Can only be set privately.
我曾经遇到过一些情况,后来决定要代理一个对象或添加AOP,这基本上需要属性。
公共属性通过公开的getter和setter方法访问字段和内部类代码。公共字段直接访问字段。
使用属性提供了一层抽象和设计的潜力(能够使set访问器受保护、私有)。
当指定属性且没有主体时,编译器会创建一个基础的私有字段来存储值。本质上:
private int item = 0;
public int Item {
get { return item; }
set {item = value; }
}