我有一个应用程序被构造为一个服务层,它使用存储库层进行持久化。 我想创建一个泛型控制器类来重用共享行为,但我在尝试设置泛型参数时遇到了问题。以下代码:隐式转换en C#泛型类
public class BusinessEntity
{ }
public class Person : BusinessEntity
{ }
public interface IRepository<T> where T : BusinessEntity
{ }
public interface IService<T, R>
where T : BusinessEntity
where R : IRepository<T>
{ }
public partial interface IPersonRepository : IRepository<Person>
{ }
public interface IPersonService : IService<Person, IPersonRepository>
{ }
public abstract class BaseController<X, Y>
where X : BusinessEntity
where Y : IService<X, IRepository<X>>
{ }
public class PersonController : BaseController<Person, IPersonService>
{ }
在编译失败并
类型ConsoleApplication.IPersonService
不能在通用类型或方法ConsoleApplication.BaseController<X,Y>
被用作类型参数Y
。有一个从ConsoleApplication.IPersonService
到ConsoleApplication.IService<ConsoleApplication.Person,ConsoleApplication.IRepository<ConsoleApplication.Person>>
这个作品
public interface IPersonService : IService<Person, IRepository<Person>>
没有隐式引用转换,但我失去了自定义库
有一种方法,使编译器实现IPersonRepository
是IRepository<Person>
?
权,这是因为'IRepository其中X:Person'是不一样的'IRepository '默认情况下,默认情况下这种通用类型没有差异。你正在使用哪个版本的.NET Framework? –
sll
2012-03-07 19:51:54
如果我有能力,我会给你一个“打破编译器”徽章。从我花了5分钟的时间努力使其工作,我的直觉结论是,编译器不够聪明,无法做你想做的事情。 – PlayDeezGames 2012-03-07 20:03:21
我正在使用.Net 4.我没有想过差异,我认为它值得一试。 – 2012-03-08 21:55:23