2012-04-26 24 views
1

可能重複的類型:
Reflection - Getting the generic parameters from a System.Type instance
Get actual type of T in a generic List<T>獲取T的泛型列表<T>對象

我通過從一類的PropertyInfo名錄循環。 在本課中,我對不同的列表感興趣 - 例如List<int>,List<string>,List<Book>,aso。

但我不知道如何得到列表對象的類型。我只是得到類似

System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, 
PublicKeyToken=b77a5c561934e089]]. 

我可以拆解本信息,並創建一個類型超出此信息,但我希望有一個平滑的方式嗎?

+0

@gdoron:同樣的答案,但。 – 2012-04-26 21:26:38

回答

8

簡單:

Type type = list.GetType().GetGenericArguments()[0]; 
// The first argument will be the `T` inside `List<T>`... so the list type ;) 
3
var list = GetListFromFoo(); 
Type listType = list.GetType(); 
Type theTypeOfT = listType.GetGenericArguments()[0]; 

或用一條線:

list.GetType().GetGenericArguments()[0];