[英]Don't allow grandchildren of abstract classes to override their parent c#
// This class just offers a public interface for triggering events
public abstract class TriggerActivator
{
public void ActivateTrigger(){
OnTriggerActivate();
}
protected abstract void OnTriggerActivate();
}
// This class does some important work, but looks for specific information returned from its child
public abstract class RaycastTriggerActivator : TriggerActivator
{
protected override void OnTriggerActivate()
{
// Do some important raycast-related stuff...
bool specificImportantInfo = SpecifyImportantInfo();
// Do some more stuff...
}
protected abstract bool SpecifyImportantInfo();
}
// This class basically gives the parent info it needs based on a specific input type
public class MouseRaycastTriggerActivator : RaycastTriggerActivator
{
protected override bool SpecifyImportantInfo() => IsMouseButtonPressedDown();
}
// OR
public class ControllerRaycastTriggerActivator : RaycastTriggerActivator
{
protected override bool SpecifyImportantInfo() => IsControllerButtonPressedDown();
}
但是,有人可以轻松破坏此功能:
public class MouseRaycastTriggerActivator : RaycastTriggerActivator
{
protected override bool SpecifyImportantInfo() => IsMouseButtonPressedDown();
/// It is important for this class's parent to implement this method,
/// but now this class is hiding its parent's implementation
protected override void OnTriggerActivate()
{
/// This guy can hide RaycastTriggerActivator's functionality
/// and break the whole system
}
}
如果有人对系统不够了解,我可以看到这种情况发生,在可用函数列表中看到 OnTriggerActivate 来覆盖,并认为他们需要使用它。
我的问题是,如果 B : A 和 A 有一个供 B 实现的抽象方法,是否有办法对 C : B 隐藏该抽象方法,如果该方法不是专门为 C 提供实现的? (":" = "继承自")
我是不是太担心这个了? 我不明白这对整个程序是如何构成安全风险的。
您可以使用 Sealed 关键字来防止 C 覆盖 B 实现的方法,如下所示:
public abstract class A
{
protected abstract void SomeFunction();
}
public class B : A
{
protected override sealed void SomeFunction()
{
//do something
}
}
现在,如果您尝试在 C 中实现 SomeFunction(),如下所示:
public class C : B
{
protected override void SomeFunction()
{
//do something different
}
}
您将在 IDE 中收到一个错误,并且您将无法编译:
'C.SomeFunction()': 不能覆盖继承的成员 'B.SomeFunction()' 因为它是密封的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.