我在编写一个使用泛型的类时遇到了一些麻烦,因为这是我第一次创建一个使用泛型的类.
我要做的就是创建一个将List转换为EntityCollection的方法.
我正在编译器错误:类型"T"必须是引用类型,以便在通用类型或方法"System.Data.Objects.DataClasses.EntityCollection"使用它作为参数"TEntity"
这是我尝试使用的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
它抱怨EntityCollection集合=新的EntityCollection()代码行.
如果有人能帮助我解决这个错误,或者向我解释我收到它的原因,我将非常感激.谢谢.
DrP*_*zza 14
阅读.NET中的通用约束.具体来说,您需要一个"where T:class"约束,因为EntityCollection不能存储值类型(C#结构),但是无约束T可以包含值类型.您还需要添加一个约束来表示T必须实现IEntityWithRelationships,因为EntityCollection需要它.这导致如下:
public static EntityCollection<T> Convert<T>(List<T> listToConvert) where T : class, IEntityWithRelationships
Run Code Online (Sandbox Code Playgroud)
您必须将类型参数T约束为引用类型:
public static EntityCollection<T> Convert(List<T> listToConvert) where T: class
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
815 次 |
| 最近记录: |