让 C# 创建使用自动属性创建(即 {get; set})生成的私有支持字段有什么缺点吗?
我知道它是自动的,因此您无法自定义获取/设置,并且想知道是否还有其他含义。
谢谢!
让 C# 创建使用自动属性创建(即 {get; set})生成的私有支持字段有什么缺点吗?
我知道它是自动的,因此您无法自定义获取/设置,并且想知道是否还有其他含义。
谢谢!
我遇到的最大问题是在查看绑定场景时它通常非常有限。通常在使用数据绑定时,您需要实现自动属性不支持的INotifyPropertyChanged 。
如果您正在使用BinaryFormatter
,更改为(或从)自动实现的属性是一项重大更改,因为字段名称对 BF 很重要。当然,一个简单的解决方法是:不要使用 BF!
您也不能使用自动属性将属性添加到支持字段。
没有字段初始化程序。
不适readonly
用于不变性。
显然,您不能添加逻辑;没有懒惰、验证、副作用或通知事件。
使用结构,您需要调用:this()
自定义构造函数,这很丑陋。
否则:他们很棒。我是个大粉丝。
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.