什么是使用自动实现的属性的默认访问,而不是使用公共领域的优势在哪里? [英] What is the advantage of using auto-implemented properties with the default access, instead of using public fields?

查看:186
本文介绍了什么是使用自动实现的属性的默认访问,而不是使用公共领域的优势在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
C#:公共领域与自动属性结果
我是否需要使用{搞定;组; }以获取和设置时没有特殊动作C#领域






考虑到这些两个选项:

 公众诠释美孚{搞定;组; } 

公众诠释美孚;



他们似乎是语义等价的,我相信他们甚至会编译为相同的IL。那么,什么是使用属性的优势在哪里?眼看着公共领域让我感到不安,但我想不出任何具体的优势,使用的财产,而不是语法。如果一个明确的getter和setter的未来是必需的,公众诠释美孚; 可以通过替换公众诠释美孚{...} 没有必要的其他变化。我能想出的最好的是该属性的语法只是感觉的更好,但我几乎不能用这个理由来说服别人。



是什么?在这种情况下使用的属性语法的优点(如果有的话)

解决方案

的主要优点是:


  1. 面向未来的API - 如果以后需要在getter或setter的逻辑,你的公共API并不能改变
  2. $ b。 $ b
  3. 数据绑定 - 大多数数据绑定框架仅针对属性,不能下地干活


Possible Duplicate:
C#: Public Fields versus Automatic Properties
Do I need to use { get; set; } with c# fields that have no special actions when getting and setting

Consider these two options:

public int Foo { get; set; }

public int Foo;

They seem to be semantically equivalent, and I believe they will even compile to the same IL. So what is the advantage of using the property? Seeing a public field makes me feel uneasy, but I can't think of any concrete advantage to using the property syntax instead. If an explicit getter and setter are required in the future, public int Foo; can be replaced by public int Foo { ... } with no other changes necessary. The best I can come up with is that the property syntax just feels better, but I can hardly use this reason to convince someone else.

What is the advantage (if any) of using the property syntax in this case?

解决方案

The main advantages are:

  1. Future-proofing your API - If you later need logic in the getter or setter, your public API doesn't change.
  2. Data binding - Most data binding frameworks only work against Properties, not Fields.

这篇关于什么是使用自动实现的属性的默认访问,而不是使用公共领域的优势在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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