为什么要使用简单的属性,而不是字段C#? [英] Why use simple properties instead of fields in C#?

查看:154
本文介绍了为什么要使用简单的属性,而不是字段C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能显示的文件:结果
  <一href=\"http://stackoverflow.com/questions/1277572/should-i-use-public-properties-and-private-fields-or-public-fields-for-data\">Should我使用的公共属性和私有字段或对数据的公共字段?结果
  <一href=\"http://stackoverflow.com/questions/1216958/difference-between-automatic-properties-and-public-field-in-c-3-0\">Difference自动属性和C#的公共领域之间3.0

人们似乎教条坚持在田野中使用的公共属性,但为什么它如此简单属性的情况下?

People seem to dogmatically insist on the use of public properties over fields but why is it so ultra-important in the case of simple properties?

如何

public int Foo { get; set; }

所以比

public int Foo;

把我的头,我能想到的,两者之间一些实际差别顶部:

Off the top of my head I can think of few practical differences between the two:


  • 访问使用反射成员(罕见的,最得体的反射算法将占差)

  • 第二项允许您使用该字段作为ref和out参数的有效参数,这似乎是一个优势,使用领域版本

  • 字段不会在远程工作(可能是,我从来没有用过远程但我想他们不会)?
  • Accessing the member using reflection (rare, and most decent reflective algorithms will account for the difference)
  • The second entry allows you to use the field as a valid parameter for ref and out parameters, which would seem to be an advantage to using the field version
  • Fields don't work in Remoting (probably, I've never used remoting but I imagine they wouldn't)?

除了这些相当罕见的情况下,改变富是一个计算的属性后会导致零线code的改变。

Other than these fairly rare cases, changing Foo to be a computed property later results in 0 lines of code changed.

推荐答案

使用属性有几个明显的优势:

Using properties has a couple of distinct advantages:


  • 它允许版本如果以后你需要额外的逻辑。添加逻辑的getter或setter不会破坏现有的code。

  • 它允许数据绑定正常工作(大多数数据绑定框架不下地干活)。

在此外,几乎没有缺点。像这样的简单,自动属性由JIT编译器内联得到,所以没有理由不使用它们。

In addition, there are almost no disadvantages. Simple, automatic properties like this get inlined by the JIT compiler, so there is no reason not to use them.

另外,你提到的:

除了这些相当罕见的情况下,改变富是一个计算的属性后会导致零线code的改变。

Other than these fairly rare cases, changing Foo to be a computed property later results in 0 lines of code changed.

这并不需要你的code被改变,但它迫使你重新编译所有的code的。从现场一个属性更改为一个破API的变化,这将需要它引用你的程序集进行重新编译的程序集。通过使自动属性,你可以运送一个新的二进制文件,并保持API兼容性。这是版本的优势我上面提到...

This doesn't require your code to be changed, but it does force you to recompile all of your code. Changing from a field to a property is a breaking API change which will require any assembly which references your assembly to be recompiled. By making it an automatic property, you can just ship a new binary, and maintain API compatibility. This is the "versioning" advantage I mentioned above...

这篇关于为什么要使用简单的属性,而不是字段C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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