我有多个控制器,有一些常见的操作。我制作了通用控制器:
public class FirstBaseController<TEntity> where TEntity : class, IFirst, new()
public class SecondBaseController<TEntity> where TEntity : class, ISecond, new()
然后我想做这样的事情:
public class MyController : FirstBaseController<First>, SecondBaseController<Second>
我知道C#中不允许多类继承。你能告诉我其他方法吗?
答案 0 :(得分:2)
唯一的选择是通过接口替换基类,并通过组合实现重用:
public interface IMyFirstSetOfMethods<TEntity> { /*... */ }
public interface IMySecondSetOfMethods<TEntity> { /*... */}
public class FirstImpl
{
}
public class SecondImpl
{
}
public class MyController : IMyFirstSetOfMethods<First> , IMySecondSetOfMethods<Second>
{
FirstImpl myFirstImpl = new FirstImpl();
SecondImpl mySecondImpl = new SecondImpl();
// ... implement the methods from the interfaces by simply forwarding to the Impl classes
}