我有一個基類,它有一些抽象方法,並有21個類從這個基類繼承。現在對於那些抽象方法之一,我希望用21個類中的6個的通用實現來實現它,所以我想創建另一個可以實現這一點的基類。您可以用另一個基類重寫基類中的某個抽象方法嗎?
我願意接受建議,但我創建當前基類和21類之間的另一個基類的主要目的是從重複相同的代碼在21班的6,如果我沒有繼續。
這裏是一個代碼示例來說明情況:
public abstract class FooBase
{
public abstract string Bar();
public abstract string SomeMethod();
public virtual string OtherMethod()
{
return this.SomeMethod();
}
}
public abstract class AnotherBase : FooBase
{
public abstract string Bar();
public abstract string SomeMethod();
public override OtherMethod()
{
//this is the common method used by 6 of the classes
return "special string for the 6 classes";
}
}
public class Foo1 : FooBase
{
public override string Bar()
{
//do something specific for the Foo1 class here
return "Foo1 special string";
}
public override string SomeMethod()
{
//do something specific for the Foo1 class here
return "Foo1 special string";
}
}
public class Another2 : AnotherBase
{
public override string Bar()
{
//do something specific for the Another2 class here
return "Another special string";
}
public override string SomeMethod()
{
//do something specific for the Another2 class here
return "Another2 special string";
}
}
你的想法似乎是正確的。你試過了嗎?你遇到過任何問題嗎? – Benesh