自动实现的获取/设置属性
让 C# 创建通过使用自动属性创建(即 {get; set})生成的私有支持字段是否有任何缺点?
我知道它是自动的,因此您无法自定义获取/设置,并且想知道是否有任何其他影响。
谢谢!
Is there any downside to letting C# create the private backing fields that are generated by using the automatic property creation (ie {get; set})?
I am aware that it is automatic and therefore you cannot customize the get/set, and would like to know if there are any other implications.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我遇到的最大问题是,在查看绑定场景时它通常非常有限。通常,在使用数据绑定时,您需要实现 INotifyPropertyChanged ,其中自动属性不支持。
The biggest issue that I have come across is that it is often very limiting when looking at binding scenarios. Typically when using data binding you need to implement INotifyPropertyChanged which is not supported by the automatic properties.
如果您使用
BinaryFormatter
,更改(或更改)自动实现的属性是一项重大更改,因为字段名称对 BF 很重要。当然,一个简单的解决办法就是:不要使用 BF!您也无法使用自动属性将属性添加到支持字段。
没有字段初始化程序。
没有真正的用于不变性的
readonly
。显然,你无法添加逻辑;没有惰性、验证、副作用或通知事件。
对于结构,您需要在自定义构造函数上调用
:this()
,这很丑陋。但除此之外:他们很棒。我是它的忠实粉丝。
If you are using
BinaryFormatter
, changing to (or from) automatically implemented properties is a breaking change, since field names matter to BF. Of course, one easy fix there is: don't use BF!You also can't add attributes to the backing field using automatic properties.
No field initialisers.
No true
readonly
for use with immutability.You can't add logic, obviously; no laziness, validation, side-effects or notification events.
With structs, you need to call
:this()
on custom constructors, which is ugly.Otherwise though: they are great. I'm a big fan.
最大的问题是您无法使用支持字段,因为它们是由编译器创建的。这意味着您不能将它们声明为 const 或 readonly,这意味着您不能添加有关访问它们的逻辑(例如延迟初始化)等。好消息是,从 autoproperty 开始可以重构为使用支持字段很简单,只要你有理由。
The biggest problem is that you can't work with the backing fields, since they are created by the compiler. This means you can't declare them const or readonly, it means you can't add logic around accessing them (lazy initialization, for example), etc. The good news is that starting with the autoproperty makes the refactor to using a backing field easy, when you have a reason.