1

我有多个具有一些常见操作的控制器。我制作了通用控制器:

 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# 中不允许多类继承。你能告诉我另一种方法吗?

4

1 回答 1

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
}
于 2012-11-28T07:27:22.843 回答