我应该使用公共属性和私有字段还是公共字段来获取数据? [英] Should I use public properties and private fields or public fields for data?

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

问题描述

在我看过的大部分代码中(在SO上,thecodeproject.com和我倾向于在我自己的代码中这样做),我看到为一个类包含的每一个私有字段创建公共属性,即使他们是最基本的 get类型; set; like:

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;

如果我们应该使用属性而不是公共字段为什么我们应该在这种特殊情况下使用它们? (我不是说更复杂的例子,其中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!

推荐答案

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

具体



  • 您不能对变量执行数据绑定。

  • 将变量更改为属性是一个突变。

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

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