除了在setter中对值进行健全性检查之外,是否存在更基本的原因来优先选择属性而不是公共变量?
我们之前提到过这个主题,但现在我找不到任何相关内容。
简而言之:你的需求可能会发生变化:如果现在没有进行合理性检查,在将来可能需要进行检查。然而,如果您将公共字段更改为属性,则会破坏二进制兼容性:每个使用您的代码/库的客户端都必须重新编译。
这是很糟糕的,因为这可能会花费大量的金钱。
从一开始就使用属性可以避免这个问题。这甚至适用于不是库的代码。为什么?因为你永远不知道:即使是高度特定于领域的代码!也可能证明有用,所以你想将其重构为一个库。如果您已经使用属性代替公共/受保护的字段,则此重构过程显然变得更加容易。
此外,在C#3.0中编写公共属性很容易,因为您可以使用自动实现的属性,节省了相当多的代码:
public DataType MyProperty { get; set; }
我会替你实现必要的后备字段和getter/setter代码。
我想补充一句:.NET在这方面的行为有点懒惰。编译器可以动态将公共字段更改为属性,从而避免这个问题。VB6已经对公开的COM类执行了此操作,我认为VB.NET和C#没有理由不这样做。也许编译器团队中的某个人(Jared?)可以对此发表评论。
简言之:
readonly
关键字怎么样? - Aaron FrankeThere are valid reasons to make a trivial property, exactly as depicted above:
- Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
- You can't databind against a variable.
- Changing a variable to a property is a breaking change.
It's a shame there's so much meaningless friction between variables and properties; most of the time they do the exact same thing. Kevin Dente proposed a bit of new syntax that would give us the best of both worlds:
public property int Name;
However, if the distinction between variable and property is such an ongoing problem, I wonder if a more radical solution is in order. Couldn't we ditch variables entirely in favor of properties? Don't properties do exactly the same thing as variables, but with better granular control over visibility?
ref obj.MyField
。如果您不更改源代码,则无法将MyField
更改为MyProperty
。 - Mehrdad Afshari你也可以通过属性来保护写入访问并允许读取访问:
public int Version { get; private set; }
public int Version { get; private set; }
。 - Ian R. O'Brien是的。
考虑一个现在持有字符串的公共变量,你可以简单地设置它。然而,如果你决定这个公共变量应该持有一个对象,并且这个对象应该用一个字符串初始化,那么你就必须改变所有使用原始对象的代码。但如果你使用setter,你只需要更改setter以用提供的字符串初始化对象。