2

我正在尝试使用反射来检测集合,例如List<T>. 最终,我需要在没有可用实例的情况下进行操作(即仅通过 typeof),并且希望检测超出 just 的集合List<T>,但为了简单起见,这里有一个失败的基本测试用例:

Type type = (new List<string>()).GetType();
if (type.IsAssignableFrom(typeof(System.Collections.IEnumerable)))
{
    Console.WriteLine("True.");
}
else Console.WriteLine("False.");

我也尝试过IListICollection但无济于事。

在进行故障排除时,我遇到了以下讨论: 为什么 List<int> 不是 IEnumerable<ValueType>?

该讨论的 OP 找到了他的答案,因为协方差对它们不起作用,所以不会被上面的东西检测到值类型。但是我使用的是字符串,一种引用类型,但仍然没有看到协方差。更奇怪的是(无论如何对我来说),当我运行上述讨论中的示例代码时,我看到了一个非常不同的结果:

System.Collections.Generic.List`1[AssignableListTest.Program+X] is most likely a list of ValueTypes or a string
System.Collections.Generic.List`1[System.String] is most likely a list of ValueTypes or a string
System.Collections.Generic.List`1[AssignableListTest.Program+Z] is most likely a list of ValueTypes or a string
System.Collections.Generic.List`1[System.Int32] is most likely a list of ValueTypes or a string
blah is most likely a list of ValueTypes or a string
1 is not a list

让我相信我必须与那张海报有配置差异。我使用的是 Visual Studio 2005,在本例中是 .NET 3.5,但如果可能的话,我需要将兼容性恢复到 2.0。实际上,如果我能得到海报的结果,就足够了(确定IEnumerable已实现),但是当我使用Type.IsAssignableFrom()“is”代替时,它们都给出“不是列表”。

4

1 回答 1

6

您需要翻转支票:

type.IsAssignableFrom(typeof(System.Collections.IEnumerable))

变成

typeof(System.Collections.IEnumerable).IsAssignableFrom(type)

每个人都至少犯过一次这个错误。这是一个误导性的 API。

于 2012-11-23T19:30:55.637 回答