c# 3.0 中的新自动属性,有什么好处?
有什么好处:
public string User {get; set;}
结束
public string User;
既然在第一种情况下您无法访问私有成员,那么仅将您的属性设为公开有什么不同?
Since you can't access the private member in the first case, how is it any different that just making your property public?
第二个示例是将 field 设为公开,而不是属性(您的问题).这提供了一种制作简单属性的简单方法.属性应该是你的默认值,而不是公共字段;原因不胜枚举,但从以下几点开始:
The second example is making the field public, not a property (your question). This provides a simple way of making simple properties. Properties should be your default, not public fields; the list of reasons is endless, but starts with:
- 封装
- 能够添加通知
- 封装
- 进行验证的能力
- 封装
- 数据绑定
- 封装
- 安全检查
哦 - 我有没有提到封装?
oh - and did I mention encapsulation?
事后将字段更改为属性是一项重大更改 - 特别是如果您使用大量引用"代码或可变结构(yeuch).
Changing from a field to a property after-the-fact is a breaking change - especially if you use a lot of "ref" code or mutable structs (yeuch).