为什么更喜欢属性而不是公共变量? [英] Why prefer Properties to public variables?
问题描述
其他能够对 setter 中的值进行完整性检查的功能是否有更深层的原因让我们更喜欢属性而不是公共变量?
Other being able to sanity check values in a setter is there a more underlying reason to prefer properties to public variables?
推荐答案
我们以前有过这个主题,但我现在找不到任何东西.
We've had this subject before but I can't find anything now.
简而言之:您的需求可能会发生变化:如果现在没有健全性检查,将来可能需要.但是,如果您将公共字段更改为属性,则会破坏二进制兼容性:使用您的代码/库的每个客户端都必须重新编译.
In brief: your needs might change: where there's no sanity check now, one might be required in the future. However, if you change your public fields to properties, this breaks binary compatiblity: every client who uses your code/library would have to re-compile.
这很糟糕,因为它可能会花费很多钱.
This is bad because it potentially costs a lot of money.
从一开始就使用属性可以避免这个问题.这甚至对于不属于库的代码也很重要.为什么?因为你永远不知道:代码(即使是高度特定于领域的!)可能证明是有用的,所以你想将它重构为一个库.如果您已经在使用属性代替公共/受保护字段,那么这种重构过程显然会变得更加容易.
Using properties from the beginning avoids this problem. This even counts for code that is not part of a library. Why? Because you never know: the code (even if highly domain-specific!) might prove useful so you want to refactor it to a library. This refactoring process is obviously made much easier if you are already using properties in place of public/protected fields.
此外,在 C# 3.0 中编写公共属性很容易,因为您可以只使用自动实现的属性,从而节省大量代码:
Additionally, writing public properties is easy in C# 3.0 because you can just use the auto-implemented properties, saving you quite a bit of code:
public DataType MyProperty { get; set; }
将为您实现必要的支持字段和 getter/setter 代码.
Will implement the necessary backing field and getter/setter code for you.
我要补充一点个人意见:.NET 在这方面的行为有点懒惰.编译器可以动态地将公共字段更改为属性,从而避免这个问题.VB6 已经为 COM 公开的类做了这件事,我认为 VB.NET 和 C# 绝对没有理由不这样做.也许编译器团队的某个人(Jared?)可以对此发表评论.
I will add a personal note: .NET's behaviour in this regard is somewhat lazy. The compiler could just change public fields to properties on the fly, thus avoiding the problem. VB6 already did this for COM-exposed classes and I see absolutely no reason for VB.NET and C# not to do the same. Perhaps someone on the compiler teams (Jared?) could comment on this.
这篇关于为什么更喜欢属性而不是公共变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!