例子如下:
1
public
class
A
2 {
3 private / protected String _strField;
4
5 public String StrProperty { get ; set ;}
6
7 public void Do1()
8 {
9
//
Other logic
10 String a = _strField; || String a = StrProperty;
11
//
Other logic
12 }
13
14 public void Do2()
15 {
16
//
Other logic
17 _strField = x; || StrProperty = x;
18
//
Other logic
19 }
20 }
2 {
3 private / protected String _strField;
4
5 public String StrProperty { get ; set ;}
6
7 public void Do1()
8 {
9


10 String a = _strField; || String a = StrProperty;
11


12 }
13
14 public void Do2()
15 {
16


17 _strField = x; || StrProperty = x;
18


19 }
20 }
在这里例子里面,我想问的是在类A的Do1和Do2方法中,我们该用_strField直接读/写数据,还是使用StrProperty?
这个问题我已经碰到过很多次了,查看微软SDK代码后,发现微软有时候直接使用字段,也有时候直接使用属性,当然大部分是字段。如果使用字段访问数据的话,子类是无法对其进行扩展的,比如在父类中使用_strField = x进行赋值,而子类继承于父类想要在StrProperty的值被更改的时候触发通知,那么子类只能在自己实现的代码触发通知,而子类继承于父类的代码中则不能做这样的检验。如果在父类是使用StrProperty的话,子类可以通过Override这个属性添加出发通知逻辑。但这样又好像破坏了类A的封装性。
目前,我倾向于直接在父类A中使用StrProperty进行数据访问,虽然从一定程度上它破坏父类的封装性。这也是目前的一种折中方案,不知道各位有什么想法。