【发布时间】:2014-03-12 15:00:12
【问题描述】:
我有一个基类,上面有一些抽象方法,并且有 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";
}
}
【问题讨论】:
-
你的想法似乎是正确的。你试过了吗?你遇到什么问题了吗?
标签: c# inheritance abstract-class