2015-09-18 85 views
0

是否有可能讓實現類定義接口的通用參數?換句話說,從實現中派生通用參數?通用接口需要類型參數

在下面的示例中,我希望能夠使用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

行號有點冗餘.. –

+0

'IRepository'具有'T'參數。你期望編譯器應該做什麼? –

+0

第9行中沒有定義「T」? – JDawg

回答

3

你可以用GenericClass<Y>多態地處理GenericClass<T>,其中TY是不同的類嗎?

不,那很重要。您希望TY之間的類型安全,這是泛型提供的。

我注意到你說你可以打印兩個控制檯,這是真的,因爲兩者都有ToString()方法。如果你想要一組擁有這種能力的物體,你需要GenericClass<object>

IGenericInterface<O>N : OM : O混合IGenericInterface<N>IGenericInterface<M>被稱爲協方差和is a bit complex,這是一個界面件事is implemented when creating the interface

相關問題