我应该使用数据公共属性和私人领域和公共领域?领域、属性、私人、数据

2023-09-02 20:41:35 作者:大陆马子装港逼〞

在大部分的code我所看到的(上如此,codeproject.com我倾向于这样做在自己的code),我已经看到了每一个被创造的公共属性私有字段,一个类包含,即使它们是获取最基本的类型;设置; 这样的:

In much of the code I have seen (on SO, thecodeproject.com 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;

和我们是否应该使用属性,而不是我们为什么要使用他们在这种特殊情况下的公共领域? (我说的不是更复杂的例子,其中的getter和setter方法​​实际做一些特别的东西,或只有一个get或set(读/只写),而不是仅仅返回/设置一个私有字段的值)。它似乎并没有增加任何额外的封装,只提供一个很好的图标,智能感知和被放置在一个特殊的部分类图!

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!

推荐答案

请参阅本文 http://blog.codinghorror.com/properties-vs-public-variables/

特别

反射原理不同的变量与属性,因此,如果你靠反射,它更容易使用的所有属性。 您不能对数据绑定的变量。 更改变量属性是一个重大更改。
 
精彩推荐
图片推荐