gpt4 book ai didi

c# - 列表、反射、IEnumerable 和配置问题

转载 作者:行者123 更新时间:2023-12-03 19:15:05 27 4
gpt4 key购买 nike

我正在尝试使用反射来检测诸如 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",他们都给出“不是列表”。

最佳答案

您需要翻转支票:

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

成为

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

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

关于c# - 列表、反射、IEnumerable 和配置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13534829/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com