为什么宁愿属性公共变量? [英] Why prefer Properties to public variables?

查看:129
本文介绍了为什么宁愿属性公共变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其他能够在二传手完整性检查值是否有一个更深层的原因喜欢属性公共变量?

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#不这样做。也许有人编译器团队(贾里德?)可以在此发表评论。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆