Skip to main content
 首页 » 编程设计

that is generic, 但匹配所有特定类型(IEnumerableint>、IEnumerableobject>、...)" rel="bookmark">c#之比较泛型 : A "master-type" IEnumerable> that is generic, 但匹配所有特定类型(IEnumerableint>、IEnumerableobject>、...)

2024年02月06日17小虾米

我想将 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; 
}