簡體   English   中英

泛型類型的泛型集合

[英]Generic collection of generic types

我想知道什么是解決此問題的最佳方法:

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

好吧,我知道這將不會編譯,但它表明了我的觀點。 我需要根據傳遞給T1的通用類型創建一個收集類型,並且該類型應包含T2類型的elementy,

深淵的想法? 提前致謝

您可以通過反射來完成。 否則,我建議您根據可能的T1列表使用接口。 像這樣:

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

你的意思是這樣嗎?

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

如果您在編譯時不知道類型,則需要將通用類型與反射綁定。 Microsoft上的這篇文章可能滿足您的需求。

最簡單的是這樣的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM