通用接口需要类型参数
问题描述:
是否有可能让实现类定义接口的通用参数?换句话说,从实现中派生通用参数?通用接口需要类型参数
在下面的示例中,我希望能够使用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线的水平。
答
你可以用GenericClass<Y>
多态地处理GenericClass<T>
,其中T
和Y
是不同的类吗?
不,那很重要。您希望T
和Y
之间的类型安全,这是泛型提供的。
我注意到你说你可以打印两个控制台,这是真的,因为两者都有ToString()
方法。如果你想要一组拥有这种能力的物体,你需要GenericClass<object>
。
下IGenericInterface<O>
时N : O
和M : O
混合IGenericInterface<N>
和IGenericInterface<M>
被称为协方差和is a bit complex,这是一个界面件事is implemented when creating the interface。
行号有点冗余.. –
'IRepository'具有'T'参数。你期望编译器应该做什么? –
第9行中没有定义“T”? – JDawg