【发布时间】:2010-08-19 20:02:14
【问题描述】:
当 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% 相信的。我正在做更强大的测试。
我很好奇,有没有更好的方法来实现这个方法?我真的不喜欢演员表,
IEnumerator extractor = ((ICollection)extractors).GetEnumerator();
【问题讨论】:
-
你不喜欢演员阵容的哪一点?
-
如果我能帮上忙,我总是尽量不投。我意识到在 if 我已经检查了分配能力的正文中。但我不确定 typeof(ICollection) 是否为真,那么演员阵容是否有效?
-
我现在正在添加测试来验证这一切。我更普遍的问题是我真正感兴趣的是,有没有人知道实现此方法的更好方法?
-
是的。
ICollection<>实现了ICollection,所以转换不会失败。但如果是我,我会做一个'as'演员并测试null。我也可能会测试/转换IEnumerable而不是ICollection,除非您需要关于ICollection接口的一些非常具体的内容。 -
@Toby,
ICollection<T>不保证ICollection的实现。 BCL 集合实现了两者,但自定义集合可能实现也可能不实现。