公共变量 - 需要属性 C#
可能的重复:
C#:公共字段与自动属性
我读到 C# 中的属性是声明或使用的向其他人提供私人成员的访问权限。那么,我们在声明public成员的时候,是不是还得为他们声明属性呢?
在下面的示例中,他们为公共成员声明了属性。我不知道为什么?
class Customer
{
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
}
谢谢!
Possible Duplicate:
C#: Public Fields versus Automatic Properties
I read properties in C# are declared or used to provide access of private members to others. In that case, when we are declaring public members, do we still have to declare properties for them.
In the following example, they have declared properties for public members. I don't know why ?
class Customer
{
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
}
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用属性而不是公共字段可以在下一个版本中对这些属性的实现方式进行非破坏性更改 - 使用公共字段时,任何更改都会破坏。
例如,您可以更改
TotalPurchases
的实现来执行计算,而不是直接返回支持字段的值。从类的使用者的角度来看,此更改是非破坏性的,不会影响应用程序的工作方式。Using properties instead of public fields allows non-breaking changes in how these properties are implemented in the next release - with public fields any change is breaking.
For example you could change the implementation of
TotalPurchases
to perform a calculation instead of returning the value of a backing field directly. From the point of view of the consumer of the class this change is non-breaking and does not affect how your application works.首先,C# 中的属性被声明的原因有很多,而这根本与私有无关。
例如,您可以将 getter 设为公开,将 setter 设为私有:
此外,对于某些由反射支持的框架,它们会查找属性而不是字段。
在这种情况下,属性是必须的,即使在 getter/setter 中没有执行任何操作时它看起来毫无用处。
So first of all, properties in C# are declared for many reasons, and it's not about being private at all.
You can, for example, make the getter public and the setter private:
Also, for some frameworks backed up by reflection, they look for properties and not fields.
In this case, properties are a must, even if it looks useless when nothing is done in the getter/setter.