在工作中,经常被约定俗成的一条就是,使用属性进行数据操作,而不是使用字段。普遍的操作都是属性公有,字段私有。当然,这种约定俗成的要求也是有意义的。
字段,仅仅是作为数据访问;属性,则是创建出类似于数据访问,但是实际上却是方法调用的接口。访问属性的时候,就像访问公有的字段,不过其底层实质却是方法实现,你可以自由定义属性访问器的行为。下面就总结下属性比字段强大的地方:
1.属性易于修改
对于学校来说,每一位学生的姓名都不可能为空,那么对于属性而言,只需要在Set方法添加判断即可。
public class Student { private string name; public string Name { get { return name; } set { if (string.IsNullOrEmpty(value)) { throw new Exception("Name cannot be null"); } name = value; } } }
但是对于公有字段,那么需要查询每一个学生姓名进行判断修复,这将花费大量时间。
2.属性可支出数据的同步访问
public class Customer { private object syncHandle = new object(); private string name; public string Name { get { lock (syncHandle) { return name; } } set { if (string.IsNullOrEmpty(value)) { throw new Exception("Name cannot be null"); } lock (syncHandle) { name = value; } } } }
3.属性可以为虚的。
public class Customer { public virtual string Name { get; set; } }
4.属性可以声明为抽象的。
public interface INameValuePair<T> { string Name { get; } T Value { get; set; } }
5.可以为属性的get和set访问器制定不同的访问权限
public class Customer { public string Name { get; protected set; } }
6.支持参数的属性,索引器
public int this[int index] { get { return theValues[index]; } set { theValues[index] = value; } } int val = someObj[i];
7。创建多维索引器
public int this[int x, int y] { get { return ComputeValue(x, y); } } public int this[int x, string name] { get { return ComputeValue(x, name); } }
所有的索引器都使用this关键字声明,C#不支持为索引器命名。
8..Net Framework中的数据绑定类仅支持属性,而不支持公有数据成员。
所以,无论何时需要在类型的公有或者保护接口中暴露数据,都应该使用属性,而所有的数据成员都应该是私有的。