繁体   English   中英

需要帮助C#generics

[英]Need help with C# generics

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

我要做的就是创建一个将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集合=新的EntityCollection()代码行。

如果有人能帮助我解决这个错误,或者向我解释我收到它的原因,我将非常感激。 谢谢。

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

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

您必须将类型参数T约束为引用类型:

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

您可能会收到该错误,因为EntityCollection构造函数要求T是一个类,而不是结构。 您需要在方法上添加where T:class约束。

您需要通用约束,但也要将您的方法声明为通用,以允许此操作

  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;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM