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> ?
感谢。
在C#3.5中使用反射来确定对象的类型是否有任何方法List<MyObject>
? 例如这里:确定C#中的列表类型
Type type = customerList.GetType();
//what should I do with type here to determine if customerList is List<Customer> ?
感谢。
要添加到卢卡斯的反应,你可能会想有点防守通过确保你实际上确实有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)
Type[] typeParameters = type.GetGenericArguments();
if(typeParameters.Contains(typeof(Customer)))
{
// do whatever
}
感谢您的答复 – Victor 2010-07-22 18:44:36