今天看Delphi的e-book,看到在delphi中以一种违反访问权限规则的“欺骗”方式访问其父类。此时我想到一个问题,就是当protected对对象进行封装保护时,是有很明显的后门的。在C#中,我们很容易将protected暴露为public。例如:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
通过这种方法,我们就可以在另外的类中毫无顾忌地访问Base的Print()方法了。
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
换句话说,如果我们想暴露某个类的受保护方法或字段,OK,我们只需要生成一个wrapper类(对使用者,就好比是包装了该类,实质上是采用继承的方法),派生这个类,然后new这个受保护方法,并将其定义为public就可以了。如此一种“欺骗”的方式,轻而易举就窃取了类的受保护方法。
也就是说,通过继承的方法,我们可以提升父类设置的访问级别。当然对于父类的private是无能为力的。
所以,对于派生类而言,是应该直接派生其受保护方法呢?还是应该new一个新的,需要我们根据实际情况来选择。