简体   繁体   中英

Generic collection of generic types

I was wondering what would be the best approach To solve this:

object GetCollection(T1, T2) 
{
    return new T1<T2>;
}

Well I know this will not compile but it states my point. I need to create a collection type based on a generic type passed T1 and it should contain elementy of type T2,

Aby ideas? Thanks in advance

You can do it via reflection. Otherwise, I will recommend using interfaces based on what the list of T1s could be. Something like this:

class GenericContainerOne<T> { }

class GenericContainerTwo<T> { }

class Construct { }

static void Main(string[] args)
{
    GenericContainerOne<Construct> returnObject = (GenericContainerOne<Construct>)GetGenericObject(typeof(GenericContainerOne<>), typeof(Construct));
}

static object GetGenericObject(Type container, Type construct)
{
    Type genericType = container.MakeGenericType(construct);

    return Activator.CreateInstance(genericType);
}

You mean like this?

object GetCollection<T1, T2>() where T1 : IEnumerable<T2>, new()
{
    return new T1();
}

If you don't know the types at compile time, then you'll need to bind the generic type with reflection. This Microsoft article may cover your needs.

The simplest is like this:

object GetCollection<T1, T2>() 
{
    return Activator.CreateInstance(typeof(T1).MakeGenericType(typeof(T2)));
}

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