[英]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.