簡體   English   中英

通用接口需要類型參數

[英]Generic interface requires type argument

是否可以有一個實現類來為接口定義通用參數? 或者換句話說,從實現中派生通用參數?

在下面的示例中,無論實體類型ID如何,我都希望能夠使用Repository接口。

 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<T>GenericClass<Y>進行多態處理,其中TY是不同的類嗎?

不,這就是重點。 您需要TY之間的類型安全,這是泛型提供的。

我注意到您說您可以將兩者都打印到控制台,這是正確的,因為兩者都有ToString()方法。 如果要具有此功能的對象的集合,則需要GenericClass<object>

N : OM : O被稱為Covariance時,將IGenericInterface<N>IGenericInterface<M>IGenericInterface<O> IGenericInterface<M>下,這有點復雜 ,它是創建接口時要實現的接口

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM