2009-11-30 228 views
4

我在編寫使用泛型的類時遇到了一些麻煩,因爲這是我第一次創建一個使用泛型的類。C#泛型需要幫助

我想要做的就是創建一個方法,將List轉換爲EntityCollection。

我正在編譯器錯誤: 類型「T」必須是引用類型,以便在通用類型或方法使用它作爲參數「TEntity」「System.Data.Objects.DataClasses.EntityCollection」

這裏是我想使用的代碼:

public static EntityCollection<T> Convert(List<T> listToConvert) 
    { 
     EntityCollection<T> collection = new EntityCollection<T>(); 

     // Want to loop through list and add items to entity 
     // collection here. 

     return collection; 
    } 

據抱怨的代碼的EntityCollection收集=新EntityCollection()線。

如果有人可以幫我解決這個錯誤,或向我解釋爲什麼我收到它,我將不勝感激。謝謝。

回答

14

閱讀上的.NET泛型約束。具體而言,由於EntityCollection不能存儲值類型(C#結構體),因此需要「where T:class」約束,但不受約束的T可包含值類型。您還需要添加一個約束來說明T必須實現IEntityWithRelationships,同樣是因爲EntityCollection要求它。這導致一些諸如:

public static EntityCollection<T> Convert<T>(List<T> listToConvert) where T : class, IEntityWithRelationships 
3

您可能會遇到該錯誤,因爲EntityCollection構造函數要求T是類而不是結構。您需要在您的方法上添加where T:class約束。

5

必須約束類型參數T爲引用類型:

public static EntityCollection<T> Convert(List<T> listToConvert) where T: class 
+0

我發現這個答案有編譯最低要求。 – Andez 2015-02-04 21:49:05

3

你需要通用約束,而且申報你的方法作爲通用的允許該

private static EntityCollection<T> Convert<T>(List<T> listToConvert) where T : class,IEntityWithRelationships 
     { 
      EntityCollection<T> collection = new EntityCollection<T>(); 

      // Want to loop through list and add items to entity 
      // collection here. 

      return collection; 
     }