determine List type in C#
Is there any way using reflection in C# 3.5 to determine if type of an object List<MyObject>
?
For example here:
Type type = customerList.GetType();
//what should I do with type here to determine if customerList is List<Customer> ?
开发者_运维知识库
Thanks.
To add to Lucas's response, you'll probably want to be a little defensive by making sure that you do in fact have 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
Edit: The above code says, 'what kind of list is it?'. To answer 'is this a List<MyObject>?
', use the is
operator as normal:
isListOfMyObject = customerList is List<MyObject>
Or, if all you have is a Type
:
isListOfMyObject = typeof<List<MyObject>>.IsAssignableFrom(type)
Type[] typeParameters = type.GetGenericArguments();
if( typeParameters.Contains( typeof(Customer) ) )
{
// do whatever
}
精彩评论