【问题标题】:Don't allow grandchildren of abstract classes to override their parent c#不允许抽象类的孙子覆盖其父 c#
【发布时间】:2020-01-07 20:56:31
【问题描述】:
// 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 提供实现? (":" = "继承自")

我是不是太担心这个了?我不明白这会对整个程序造成安全风险。

【问题讨论】:

    标签: c# inheritance design-patterns


    【解决方案1】:

    您可以使用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()' 因为它是密封的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多