需要C#泛型的帮助吗
我在编写一个使用泛型的类时遇到了一些困难,因为这是我第一次创建一个使用泛型的类 我所要做的就是创建一个方法,将列表转换为EntityCollection 我收到编译器错误: 类型“T”必须是引用类型,才能将其用作泛型类型或方法“System.Data.Objects.DataClasses.EntityCollection”中的参数“TEntity” 以下是我尝试使用的代码:需要C#泛型的帮助吗,c#,generics,C#,Generics,我在编写一个使用泛型的类时遇到了一些困难,因为这是我第一次创建一个使用泛型的类 我所要做的就是创建一个方法,将列表转换为EntityCollection 我收到编译器错误: 类型“T”必须是引用类型,才能将其用作泛型类型或方法“System.Data.Objects.DataClasses.EntityCollection”中的参数“TEntity” 以下是我尝试使用的代码: public static EntityCollection<T> Convert(List<
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转换(列表listToConvert)
{
EntityCollection集合=新EntityCollection();
//要循环浏览列表并向实体添加项吗
//在这里收集。
回收;
}
它正在抱怨EntityCollection collection=new EntityCollection()代码行的错误
如果有人能帮我解决这个错误,或者向我解释为什么我会收到它,我将不胜感激。谢谢。您可能会遇到这个错误,因为EntityCollection构造函数要求T是类,而不是结构。您需要在方法上添加
其中T:class
约束。必须将类型参数T约束为引用类型:
public static EntityCollection<T> Convert(List<T> listToConvert) where T: class
公共静态EntityCollection转换(列表listToConvert),其中T:class
阅读.NET中的通用约束。具体来说,您需要一个“where T:class”约束,因为EntityCollection不能存储值类型(C#structs),但无约束的T可以包含值类型。您还需要添加一个约束,说明T必须实现EntityWithRelationships,这也是因为EntityCollection需要它。这会导致以下情况:
public static EntityCollection<T> Convert<T>(List<T> listToConvert) where T : class, IEntityWithRelationships
公共静态EntityCollection转换(列表listToConvert),其中T:class,EntityWithRelationships
您需要泛型约束,但也需要将您的方法声明为泛型以允许此操作
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;
}
私有静态EntityCollection转换(列表listToConvert),其中T:class,EntityWithRelationships
{
EntityCollection集合=新EntityCollection();
//要循环浏览列表并向实体添加项吗
//在这里收集。
回收;
}
我发现这个答案对编译的要求很低。