I have the following method which returns true when a PropertyInfo instance references an object that is a collection of IDataExtractor objects:
private bool IsCollectionOfIDataExtractors( PropertyInfo propInfo )
{
var result = false;
var extractors = propInfo.GetValue(dataExtractor, null);
if (typeof ( ICollection ).IsAssignableFrom(extractors.GetType() ) ||
typeof ( ICollection<> ).IsAssignableFrom(extractors.GetType() ) )
{
IEnumerator extractor = ((ICollection)extractors).GetEnumerator();
extractor.MoveNext();
if (typeof ( IDataExtractor ).IsAssignableFrom(
extractor.Current.GetType()) )
{
result = true;
}
}
return result;
}
When thinking about this method I searched through StackOverflow and found the following related item Accessing a Collection Through Reflection . That got me half way there.
After some testing it looks like this works, but I’m not 100% convinced. I’m working up beefier tests.
I’m curious though, is there a better way to implement this method? I don’t really like the cast statement,
IEnumerator extractor = ((ICollection)extractors).GetEnumerator();
1 Answer