确定C#中的List类型

时间:2010-07-22 18:23:49

标签: .net-3.5

有没有办法在C#3.5中使用反射来确定对象的类型List<MyObject>? 例如:

Type type = customerList.GetType();

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

感谢。

2 个答案:

答案 0 :(得分:8)

为了增加卢卡斯的回答,你可能希望通过确保你确实有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)

答案 1 :(得分:0)

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