2010-07-22 67 views
3

在C#3.5中使用反射來確定對象的類型是否有任何方法List<MyObject>? 例如這裏:確定C#中的列表類型

Type type = customerList.GetType(); 

//what should I do with type here to determine if customerList is List<Customer> ? 

感謝。

回答

6

要添加到盧卡斯的反應,你可能會想有點防守通過確保你實際上確實有List<something>

Type type = customerList.GetType(); 
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) 
    itemType = type.GetGenericArguments()[0]; 
else 
    // it's not a list at all 

編輯:上面的代碼表示, '這是什麼樣的名單?'。要回答「是這個List<MyObject>?」,使用is操作正常:

isListOfMyObject = customerList is List<MyObject> 

或者,如果你已經是一個Type

isListOfMyObject = typeof<List<MyObject>>.IsAssignableFrom(type) 
+0

感謝您的答覆 – Victor 2010-07-22 18:44:36

0
Type[] typeParameters = type.GetGenericArguments(); 
if(typeParameters.Contains(typeof(Customer))) 
{ 
    // do whatever 
}