[英]Passing in type argument to a method to be used to designate a generic type
是否可以將泛型與Type參數混合使用? 例如,有沒有辦法編寫這樣的代碼:
IList GetListOfListsOfTypes(Type[] types)
{
IList<IList> listOfLists = new List<IList>();
foreach (Type t in types)
{
listOfLists.Add(new List<t>());
}
return listOfLists.ToList();
}
很明顯,編譯器不喜歡這個,但有沒有辦法實現這一點?
要使用反射執行此操作,必須從open類型構造閉合泛型類型; 然后用反射中的一個選項構造它。 Activator.CreateInstance適用於此:
IList GetListOfListsOfTypes(Type[] types)
{
IList<IList> listOfLists = new List<IList>();
foreach (Type t in types)
{
Type requestedTypeDefinition = typeof(List<>);
Type genericType = requestedTypeDefinition.MakeGenericType(t);
IList newList = (IList)Activator.CreateInstance(genericType);
listOfLists.Add(newList);
}
return listOfLists;
}
請注意,您正在從此方法返回非泛型IList
的列表,這是必要的,因為我們在編譯時不知道類型,因此為了使用新的通用列表,您可能需要使用反射再次。 考慮它是否值得 - 當然,這取決於您的要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.