简体   繁体   English

需要帮助C#generics

[英]Need help with C# generics

I'm having a bit of trouble writing a class that uses generics because this is the first time that I have had to create a class that uses generics. 我在编写一个使用泛型的类时遇到了一些麻烦,因为这是我第一次创建一个使用泛型的类。

All I am trying to do is create a method that converts a List to an EntityCollection. 我要做的就是创建一个将List转换为EntityCollection的方法。

I am getting the compiler error: The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Objects.DataClasses.EntityCollection' 我收到编译器错误:类型'T'必须是引用类型才能在泛型类型或方法'System.Data.Objects.DataClasses.EntityCollection'中将其用作参数'TEntity'

Here is the code that I am trying to use: 这是我尝试使用的代码:

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

It is complaining about the the EntityCollection collection = new EntityCollection() line of code. 它抱怨EntityCollection集合=新的EntityCollection()代码行。

If anyone could help me out with this error, or explain to me why I am receiving it I would greatly appreciate it. 如果有人能帮助我解决这个错误,或者向我解释我收到它的原因,我将非常感激。 Thanks. 谢谢。

Read up on generic constraints in .NET. 阅读.NET中的通用约束。 Specifically, you need a "where T : class" constraint, since EntityCollection cannot store value types (C# structs), but unconstrained T can include value types. 具体来说,您需要一个“where T:class”约束,因为EntityCollection不能存储值类型(C#结构),但是无约束T可以包含值类型。 You will also need to add a constraint to say that T must implement IEntityWithRelationships, again because EntityCollection demands it. 您还需要添加一个约束来表示T必须实现IEntityWithRelationships,因为EntityCollection需要它。 This results in something such as: 这导致如下:

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

You are likely getting that error because the EntityCollection constructor requires T to be a class, not a struct. 您可能会收到该错误,因为EntityCollection构造函数要求T是一个类,而不是结构。 You need to add a where T:class constraint on your method. 您需要在方法上添加where T:class约束。

you need the generic constraint but also to declare your method as generic to allow this 您需要通用约束,但也要将您的方法声明为通用,以允许此操作

  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