【问题标题】:Lists, Reflection, IEnumerable, and a configuration issue列表、反射、IEnumerable 和配置问题
【发布时间】:2012-11-12 03:47:16
【问题描述】:

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

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

我也试过IListICollection 都无济于事。

在进行故障排除时,我遇到了以下讨论: Why is List<int> not 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”时,它们都给出“不是列表”。

【问题讨论】:

标签: c# collections reflection


【解决方案1】:

您需要翻转支票:

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

变成

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

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

【讨论】:

  • 在我个人的ReflectionUtilities 中,我实际上只在IsAssignableFrom 周围创建了两个方法包装器,其中方法/参数名称非常清楚,正是因为这个原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多