c# - 覆盖嵌套类函数或使用委托(delegate)?**

标签 c# class oop nested

我有一个基类,里面有一个嵌套类型。外部(基本)类型中有一个函数,稍后会被其子项覆盖。事实上,这个函数属于 OOinner type 但我仍然需要它,被 subtypes 覆盖基类.

我应该将此函数用作 inner typecallback 还是只是将其移动到 inner type 中,让我们的 子类型 从那里覆盖它?

编辑:添加示例代码

class A
{
    protected void func() { /* do something */ }
    class B { /**/ }
}

// OR

class A
{
    class B
    {
        protected void func() { /* do something */ }
    }
}

// Then

class C : A
{
    override func() { /**/ }
}

最佳答案

我的建议是为内部类型函数创建一个委托(delegate),它由基类的构造函数启动:

internal class BaseClass
{
    public BaseClass(Action myAction)
    {
        this.innerType = new InnerType(myAction);
    }

    public BaseClass()
    {
        // When no function delegate is supplied, InnerType should default to
        // using its own implementation of the specific function
        this.innerType = new InnerType();
    }
}

如您所见,派生类型可以使用 :base (overridenAction) 调用基类构造函数,它们可以在其中为最内层类型提供自己的函数实现。当然,您没有义务使用 Action,而是您想要的任何委托(delegate)。

关于c# - 覆盖嵌套类函数或使用委托(delegate)?**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774284/

相关文章:

c# - DataContext 并将自身绑定(bind)为 RelativeSource

c# - 如何创建和维护代码重用库?

c# - ManagementScope 能否用于从 Windows 向 Linux/MacOS 客户端发送 wbem 查询? C#

c++ - 初学者和 C++ 模板 : Is it an how possible using C++ template make a class oriented to work with chars work with costume structures?

java - 使用 super.toString 将 String 和 int 添加到父类中

c# - 抽象类使用哪个具体类?设计问题?

javascript - 强制子类不可变

c# - Prism 6 UriQuery 类丢失?

javascript - 在原型(prototype)方法中的匿名函数中访问实例变量

javascript - webpack 导出默认有效,而导出对象则无效