C#泛型类的隐式转换

时间:2012-03-07 19:48:46

标签: c# generics

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

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不能用作泛型类型或方法Y中的类型参数ConsoleApplication.BaseController<X,Y>。没有从ConsoleApplication.IPersonServiceConsoleApplication.IService<ConsoleApplication.Person,ConsoleApplication.IRepository<ConsoleApplication.Person>>

的隐式引用转换

这是有效的

public interface IPersonService : IService<Person, IRepository<Person>>

但我丢失了自定义存储库

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

2 个答案:

答案 0 :(得分:4)

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, Z>
    where X : BusinessEntity
    where Y : IService<X, Z>
    where Z : IRepository<X>
{ }

public class PersonController : BaseController<Person, IPersonService, IPersonRepository>
{ } 

解决你的意见:

  

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

如果不要求存储库类型是类型参数,IPersonService是否可以这样做?例如:

public interface IService<T> where T : BusinessEntity { } 

public interface IPersonService : IService<Person>
{
    IEnumerable<Person> FindPersonsByAge(double minAge, double maxAge);
}

public class Service<T, R> : IService<T>
    where T : BusinessEntity 
    where R : IRepository<T> 
{ }

public class PersonService : Service<Person, IPersonRepository>, IPersonService
{ }

答案 1 :(得分:0)

感谢所有人指出我正确的方向

public interface IService<T, out R>
    where T : BusinessEntity
    where R : IRepository<T>
{ }

诀窍