【发布时间】: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.");
我也试过IList 和ICollection 都无济于事。
在进行故障排除时,我遇到了以下讨论: 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”时,它们都给出“不是列表”。
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# collections reflection