为什么要使用简单的属性,而不是字段C#?

编程入门 行业动态 更新时间:2024-10-26 10:38:58
本文介绍了为什么要使用简单的属性,而不是字段C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能显示的文件:结果  Should我使用的公共属性和私有字段或对数据的公共字段?结果  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#?

本文发布于:2023-11-07 17:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567013.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   要使   而不是   属性   简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!