我有以下方法,当 PropertyInfo 实例引用作为 IDataExtractor 对象集合的对象时返回 true:
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;
}
在考虑这个方法时,我通过 StackOverflow 进行了搜索,找到了以下相关项 Accessing a Collection Through Reflection .这让我成功了一半。
经过一些测试,它看起来可行,但我并不是 100% 相信。我正在进行更强大的测试。
不过我很好奇,有没有更好的方法来实现这个方法?我真的不喜欢 Actor 声明,
IEnumerator extractor = ((ICollection)extractors).GetEnumerator();
请您参考如下方法:
var extractors = propInfo.GetValue(dataExtractor, null);
var asEnumerable = extractors as IEnumerable;
if (asEnumerable != null)
{
var enumerator = asEnumerable.GetEnumerator();
enumerator.MoveNext();
if (enumerator.Current != null)
return enumerator.Current is IDataExtractor;
}
return false;
