我有一个基类
,里面有一个嵌套类型。外部(基本)类型中有一个函数,稍后会被其子项覆盖。事实上,这个函数属于 OO
的 inner type
但我仍然需要它,被 的
.subtypes
覆盖基类
我应该将此函数用作 inner type
的 callback
还是只是将其移动到 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/