我在编写使用泛型的类时遇到了一些麻烦,因为这是我第一次不得不创建使用泛型的类。

我想要做的就是创建一个将 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;
    }

它提示 EntityCollection collection = new EntityCollection() 代码行。

如果有人可以帮助我解决该错误,或​​向我解释为什么收到此错误,我将不胜感激。谢谢。

最佳答案

阅读 .NET 中的通用约束。具体来说,您需要一个“where T:class”约束,因为EntityCollection无法存储值类型(C#结构),但是不受约束的T可以包含值类型。您还需要添加一个约束,说明 T 必须实现 IEntityWithRelationships,同样是因为 EntityCollection 需要它。这会导致诸如:

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

关于c# - 需要 C# 泛型方面的帮助,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1821885/

10-11 23:04