是否可以让实现类定义接口的泛型参数?或者,换句话说,从实现中派生泛型参数?
在下面的示例中,我希望能够使用Repository接口而不管实体类型Id。
1 class Entity<T> // where id is either an int or Guid
2 {
3 public T Id { get; set; }
4 }
5 interface IRepository<T>
6 {
7 IEnumerable<Entity<T>> ListAll();
8 }
9 class GuidRepository : IRepository<Guid> // this repo deals with Guid type entities
10 {
11 public Entity<Guid> ListAll()
12 {
13 // list all entities
14 }
15 }
16 class Program
17 {
18 private IRepository GetRepository(int someCriteria)
19 {
20 switch (someCriteria)
21 {
22 case 1:
23 return new GuidRepository();
24 ...
25 }
26 }
27 static void Main(string[] args)
28 {
29 Program p = new Program();
30 IRepository repo = p.GetRepository(1);
31 var list = repo.ListAll();
32 }
33 }
正如代码所示,编译器在第18行抱怨说:
Using the generic type requires 1 type arguments
在我的实际项目中,调用GetRepository的方法是一个MVC控制器操作,因此无法确定第16行的类型参数。
答案 0 :(得分:3)
您可以GenericClass<T>
多态地处理GenericClass<Y>
,其中T
和Y
是不同的类吗?
没有。这就是重点。您希望T
和Y
之间的类型安全,这是Generics提供的。
我注意到你说你可以打印到控制台,这是真的,因为它们都有ToString()
方法。如果您想要具有此功能的对象集合,则需要GenericClass<object>
。
当IGenericInterface<N>
和IGenericInterface<M>
被称为协方差和is a bit complex时,在IGenericInterface<O>
下混合N : O
和M : O
,它是界面的东西那is implemented when creating the interface。