在 C# 中,字段与属性有何不同,何时应使用字段而不是属性?
属性公开字段。字段应该(几乎总是)对类保持私有,并通过 get 和 set 属性进行访问。属性提供了一定程度的抽象,允许您更改字段,同时不影响使用您的类的事物访问它们的外部方式。
public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;
// this is a property. When accessed it uses the underlying field,
// but only exposes the contract, which will not be affected by the underlying field
public string MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
}
}
// This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
// used to generate a private field for you
public int AnotherProperty { get; set; }
}
@Kent 指出属性不需要封装字段,它们可以对其他字段进行计算,或用于其他目的。
@GSS 指出您还可以执行其他逻辑,例如在访问属性时进行验证,这是另一个有用的功能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)