[英]How to force overrides in a derived class from non abstract base classes?
有什么方法可以强制派生类重写其基类的虚拟方法?
在我的情况下,基类不能是抽象的,所以我不能使用抽象的方法。 所以我想知道在C#中这是否有可能?
这是我要执行的常规设置:
public abstract SomeAbstractClass {
//Test() does not belong here.
}
public ClassA : SomeAbstractClass{
protected virtual void Test(){};
}
public ClassB : ClassA{
// how can i make this mandatory in the same way abstract methods work
protected override void Test(){};
}
有可能吗?
另一个中间类是否可以接受? 如果是这样,则可以将虚拟方法作为抽象方法覆盖,这将强制继承者覆盖。
最终结果将如下所示:
public abstract class SomeAbstractClass { }
public class ClassA : SomeAbstractClass {
protected virtual void Test() { }
}
public abstract class ClassB : ClassA {
protected override abstract void Test();
}
public class ClassC : ClassB {
protected override void Test() { }
}
ClassC
被强制实现Test
以从ClassB
继承,因为Test
现在在此继承级别是抽象的。
您有无法使用界面的特定原因吗? 这听起来像是个好地方,因为它没有定义实现,因此需要任何实现该接口的类来定义方法详细信息。
除非有充分的理由要具有继承层次结构,否则我会尝试在继承上使用组合。
// Whatever your top level abstract class is
public abstract class SomeAbstarctClass
{
}
// Interface that defines the signature of the Test method, but has no implementation detail.
// No need to define it as virtual here, since there is no implementation
public interface ITestMethodInterface
{
void Test();
}
// Inherit from the absract class and implement the interface. This forces the new class to implement the interface, and therefore the Test method
public class ClassA : SomeAbstarctClass, ITestMethodInterface
{
// This CAN, if needed be virtual, but I would recommend if it isn't absolutely needed for a hierarchy to simply implement it here and use the Interface in ClassB
// to force the derviced class to implement it instead.
public void Test()
{
// Class A's implementation of Test()
}
}
// Here's where it might get complicated, if you MUST have a hierachy where Class B MUST inherit from Class A instead of SomeAbstractClass, then the implementation will carry over
// and it becomes difficult to FORCE the derviced class to override from ClassA
public class ClassB : SomeAbstarctClass, ITestMethodInterface
{
public void Test()
{
// Class B's implementation of Test()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.