关于.net继承中的私有字段
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
用sos调试
第一步:查看栈信息
!ClrStack -a
OS Thread Id: 0x840 (2112)
ESP EIP
0012f434 010400e0 MyTest.Program.Main(System.String[])
PARAMETERS:
args = 0x01312f24
LOCALS:
0x0012f440 = 0x01312f34 //创建的Chicken对象的地址
0x0012f43c = 0x01312f84 //创建的Bird对象的地址
0012f69c 79e71b4c [GCFrame: 0012f69c]
第二步:查看Chicken类的对象的信息
!DumpObj 0x01312f34
Name: MyTest.Chicken
MethodTable: 00983120
EEClass: 009813c0
Size: 20(0x14) bytes
(C:"Documents and Settings"Administrator"Desktop"TestProject"MyTest"bin"Debug"MyTest.exe)
Fields:
MT Field Offset Type VT Attr Value Name
793308ec 4000001 4 System.String 0 instance 01312f68 type
793308ec 4000002 8 System.String 0 instance 00000000 color
793308ec 4000003 c System.String 0 instance 01312f48 type
第三步:查看Bird类对象的信息
!DumpObj 0x01312f84
Name: MyTest.Bird
MethodTable: 009830a0
EEClass: 0098135c
Size: 16(0x10) bytes
(C:"Documents and Settings"Administrator"Desktop"TestProject"MyTest"bin"Debug"MyTest.exe)
Fields:
MT Field Offset Type VT Attr Value Name
793308ec 4000001 4 System.String 0 instance 01312f68 type
793308ec 4000002 8 System.String 0 instance 00000000 color
可以看到Chicken的实例中完全有Bird类的私有字段
private string type 和private string color
还有一个在Bird类中覆盖的字段type,这和方法的覆盖比较类似
但是在Chicken的实例中不能访问父类Bird的私有字段
在创建一个对象的时候引用类型(本例中b和c)不同的区别决定了访问的权限
在两个实例中 的type和color私有字段完全相同,对应的是内存中的同一位置,
但是Bird 实例的附加信息决定了Bird引用类型能访问其私有字段,而Chicken引用类型
则不能访问继承来的私有字段type和color ,因为其没有访问的权限 而不是因为在Chicken实例中不存在私有字段type和color。
欢迎拍砖。。。。。。。。。。。。。。。。。。。。。。。。。。