【问题标题】:Comparing generics: A "master-type" IEnumerable<> that is generic, but matches all specific types (IEnumerable<int>, IEnumerable<object>, ...)?比较泛型:“主类型”IEnumerable<> 是泛型的,但匹配所有特定类型(IEnumerable<int>、IEnumerable<object>、...)?
【发布时间】:2014-07-22 12:06:29
【问题描述】:

我想将 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的方法,所以基本上它反射自己的类来找到给定所需目标类型的合适转换方法。

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

我知道只使用 IEnumerable 而不是 IEnumerable 可以在这里完成这项工作,但我明确需要使用通用 IEnumerable 因为稍后,我想做进一步的反思并过滤掉所有转换为的方法泛型类型。

谢谢!

【问题讨论】:

    标签: c# generics reflection


    【解决方案1】:
    public static bool Compare(Type genericType, Type t)
    {
        return t.IsGenericType && t.GetGenericTypeDefinition() == genericType;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多