c# - 比较泛型 : A "master-type" IEnumerable<> that is generic, 但匹配所有特定类型(IEnumerable<int>、IEnumerable<object>、...)?

标签 c# generics reflection

我想将 typeof(IEnumerable<>) 与 IEnumerable 的各种特定类的类型进行比较,例如

Compare(typeof(IEnumerable<>), typeof(IEnumerable<object>))   // should return true
Compare(typeof(IEnumerable<>), typeof(IEnumerable<int>))      // should return true
Compare(typeof(IEnumerable<>), typeof(IEnumerable<MyClass>))  // should return true
Compare(typeof(IEnumerable<>), typeof(IEnumerable))           // should return FALSE because IEnumerable is not the generic IEnumerable<> type

我该怎么做?对于上述所有示例,所有常见方法(例如 == 或 IsAssignableFrom)都返回 false。


这个问题可能不是必需的,但有一些背景:

我正在编写一个将对象转换为其他类型的转换类。我正在使用属性 (XlConverts):

public class XlConvertsAttribute : Attribute
{
    public Type converts;
    public Type to;
}

标记每个方法转换成的类型。我的一种转换方法将对象转换为 IEnumerable:

[XlConverts(converts = typeof(object), to = typeof(IEnumerable<>))]
    public static IEnumerable<T> ToIEnumerable<T>(object input)
    {
    // ....
}

那我有一个更通用的方法

public static object Convert(object input, Type toType)
{
    // ...
}

它使用反射来获取具有 XlConverts.to == toType 的方法,因此基本上它反射(reflect)了它自己的类以在给定所需目标类型的情况下找到合适的转换方法。

现在当我调用 Convert(input, typeof(IEnumerable)) 时,它应该通过反射找到 ToIEnumerable 方法。但是因为我只能用 [XlConverts(to = typeof(IEnumerable<>)) 标记它,而 IEnumerable<> 不是 IEnumerable,所以它找不到这个方法。

我知道只使用 IEnumerable 而不是 IEnumerable<> 就可以完成这里的工作,但我明确需要使用通用 IEnumerable<> 因为稍后,我想做进一步的反射(reflection)并过滤掉所有转换为通用类型。

谢谢!

最佳答案

public static bool Compare(Type genericType, Type t)
{
    return t.IsGenericType && t.GetGenericTypeDefinition() == genericType;
}

关于c# - 比较泛型 : A "master-type" IEnumerable<> that is generic, 但匹配所有特定类型(IEnumerable<int>、IEnumerable<object>、...)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23993408/

相关文章:

c# - 调试 NuGet 包 - 不显示源的符号

c# - 为什么以及如何在 C# 中使用静态只读修饰符

java - 涉及通配符类型的未经检查的强制转换

java - 初始化 java 集合,将泛型留空,例如: HashMap<A, B> hM = HashMap<>();

java - 通过通用方法使单元格可编辑

c# - 用于查找属性差异的 Lambda,反射在 C# 中未正确返回

c# - 如何检索 html li 值

c# - 哪种是为应用程序编写日志的最基于性能的方法

java - 如何使用反射从 View 和 Controller 向多个 JButton 添加监听器?

c# - "Assembly.EntryPoint.Invoke"问题 [C#]