我应该使用数据公共属性和私人领域和公共领域? [英] Should I use public properties and private fields or public fields for data?

查看:265
本文介绍了我应该使用数据公共属性和私人领域和公共领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大部分的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/

特别

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

这篇关于我应该使用数据公共属性和私人领域和公共领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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