C#generics类的隐式转换

我有一个结构化为服务层的应用程序,它使用存储库层来实现持久性。 我正在尝试创建一个通用控制器类来重用共享行为,但我在尝试设置通用参数时遇到了麻烦。 以下代码:

public class BusinessEntity { } public class Person : BusinessEntity { } public interface IRepository where T : BusinessEntity { } public interface IService where T : BusinessEntity where R : IRepository { } public partial interface IPersonRepository : IRepository { } public interface IPersonService : IService { } public abstract class BaseController where X : BusinessEntity where Y : IService<X, IRepository> { } public class PersonController : BaseController { } 

编译失败

ConsoleApplication.IPersonService类型不能用作generics类型或方法ConsoleApplication.BaseController中的类型参数YConsoleApplication.IPersonServiceConsoleApplication.IService<ConsoleApplication.Person,ConsoleApplication.IRepository>没有隐式引用转换。

这很有效

 public interface IPersonService : IService<Person, IRepository> 

但我失去了自定义存储库

有一种方法可以让编译器实现IPersonRepository是一个IRepository

 public class BusinessEntity { } public class Person : BusinessEntity { } public interface IRepository where T : BusinessEntity { } public interface IService where T : BusinessEntity where R : IRepository { } public partial interface IPersonRepository : IRepository { } public interface IPersonService : IService { } public abstract class BaseController where X : BusinessEntity where Y : IService where Z : IRepository { } public class PersonController : BaseController { } 

为了解决你的评论:

IPersonService可以扩展基本服务类以添加自定义工具,如FindPersonsUnderAge()。 为此,它需要一个自定义存储库。 实际上LINQ避免了很多自定义存储库代码,但有时它们是必需的。

IPersonService无法在不要求存储库类型为类型参数的情况下执行此操作吗? 例如:

 public interface IService where T : BusinessEntity { } public interface IPersonService : IService { IEnumerable FindPersonsByAge(double minAge, double maxAge); } public class Service : IService where T : BusinessEntity where R : IRepository { } public class PersonService : Service, IPersonService { } 

谢谢你指点我正确的方向

 public interface IService where T : BusinessEntity where R : IRepository { } 

诀窍