在我看过的大部分代码中(在SO上,thecodeproject和我倾向于在我自己的代码中这样做),我看到为一个类包含的每一个私有字段创建公共属性,即使他们是最基本的 get类型; set; like:
In much of the code I have seen (on SO, thecodeproject and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of get; set; like:
private int myInt; public int MyInt { get { return myInt; } set { myInt = value } }我的问题是:这不同于:
My question is: how does this differ from:
public int MyInt;如果我们应该使用属性而不是公共字段为什么我们应该在这种特殊情况下使用它们? (我不是说更复杂的例子,其中getters和setters实际上做一些特殊的或只有一个get或set(读/写),而不是只返回/设置一个私有字段的值。它似乎没有添加任何额外的封装,只是在IntelliSense中给出一个好的图标,并放在类图中的一个特殊部分!
and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!
推荐答案请参阅这篇文章 blog.codinghorror/properties-vs -public-variables /
具体
- 您不能对变量执行数据绑定。
- 将变量更改为属性是一个突变。
更多推荐
我应该使用公共属性和私有字段还是公共字段来获取数据?
发布评论