2009-11-30 162 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; 
     }