简体   繁体   中英

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.

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'

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.

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. Specifically, you need a "where T : class" constraint, since EntityCollection cannot store value types (C# structs), but unconstrained T can include value types. You will also need to add a constraint to say that T must implement IEntityWithRelationships, again because EntityCollection demands it. 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. You need to add a where T:class constraint on your method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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