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

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

问题描述

在我看到的大部分代码中(在 SO、thecodeproject.com 上,我倾向于在我自己的代码中这样做),我已经看到为类包含的每个私有字段创建了公共属性,即使它们是最基本的 get 类型;设置; 喜欢:

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(只读/写),而不仅仅是返回/设置私有字段的值).好像没有加什么额外的封装,只是在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天全站免登陆