当我遇到这个问题时,我是C#的新手,正在学习密封类
“出于安全原因,密封类主要是通过防止意外派生而使用的,因为派生类可能会破坏派生类破坏基类中提供的实现”
这真的有可能吗?派生类真的可以破坏基类的实现吗?如果可以的话,请举例说明。
假设您需要一些门卫:
public interface IGateKeeper
{
/// <summary>
/// Check if the given id is allowed to enter.
/// </summary>
/// <param name="id">id to check.</param>
/// <param name="age">age to check</param>
/// <returns>A value indicating whether the id is allowed to enter.</returns>
bool CanEnter(string id, int age);
... other deep needs ...
}
您可能有一个可靠的实现,可以测试酒吧入口处的大多数:
public class MajorityGateKeeper : IGateKeeper
{
public virtual bool CanEnter(string id, int age)
{
return age >= 18;
}
... other deep implementation ...
}
还有一个贵宾室的实现:
public class VipGateKeeper : MajorityGateKeeper
{
public override bool CanEnter(string id, int age)
{
// Do the majotity test and check if the id is VIP.
return base.CanEnter(id, age) && (id == "Chuck Norris");
}
}
并一秒钟打破它:
public class DrunkGateKeeper : VipGateKeeper
{
public override bool CanEnter(string id, int age)
{
return true;
}
}
DrunkGateKeeper是一个VipGateKeeper,因此您可以隐藏它的醉酒(广播到VipGateKeeper)。但这做得很糟糕。
var gk = (VipGateKeeper) new DrunkGateKeeper();
var canEnter = gk.CanEnter("Miley Cyrus", 16); // true (sic)
如果将VipGateKeeper密封,则确保它不会被喝醉:VipGateKeeper类型的对象仅是VipGateKeeper。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句