I am trying to get the type of an object at runtime. In particular, I need to know two things: whether it implements ICollection or IDto. Currently, my only solution I could find is the following:
private static bool IsACollection(PropertyDescriptor descriptor)
{
bool isCollection = false;
foreach (Type type in descriptor.PropertyType.GetInterfaces())
{
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(ICollection<>))
{
isCollection = true;
break;
}
}
else
{
if (type == typeof(ICollection))
{
isCollection = true;
break;
}
}
}
return isCollection;
}
private static bool IsADto(PropertyDescriptor descriptor)
{
bool isDto = false;
foreach (Type type in descriptor.PropertyType.GetInterfaces())
{
if (type == typeof(IDto))
{
isDto = true;
break;
}
}
return isDto;
}
However, I am convinced that there must be a better way than this. I tried comparing in the usual way, for example:
if(descriptor.PropertyType == typeof(ICollection<>))
However, this does not work when using reflection, when reflection is not used, it works fine.
I do not want to iterate over the interfaces for each field of my object. Can someone shed light on another method to do this? Yes, I optimize prematurely, but it looks ugly, so please humor me.
Cautions:
- , IList < > ArrayList, ICollection ICollection < > . , IsGenericType if, , ICollection < > .
!