C#3.0 自动属性,为什么不直接访问字段? [英] C#3.0 Automatic properties, why not access the field directly?
本文介绍了C#3.0 自动属性,为什么不直接访问字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用像这样在类的属性中使用 get/set 的新方法:
With the new approach of having the get/set within the attribut of the class like that :
public string FirstName {
get; set;
}
为什么不简单地将属性 FirstName 设为 public 而没有访问器?
Why simply not simply put the attribute FirstName public without accessor?
推荐答案
直接访问类内部变量(字段/属性)的两个大问题是:
Two of the big problems with direct access to variable inside class (field/attribute) are:
1) 您不能轻松地针对字段进行数据绑定.
1) You can't easily databind against fields.
2) 如果您从类中公开公共字段,则以后不能将它们更改为属性(例如:向 setter 添加验证逻辑)
2) If you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters)
这篇关于C#3.0 自动属性,为什么不直接访问字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文