检查类型是否在不考虑泛型类型参数的情况下实现泛型接口

Jür*_*ock 29 c# generics types interface

我有一个界面

public interface MyInterface<TKey, TValue>
{
}
Run Code Online (Sandbox Code Playgroud)

实现是无关紧要的.现在我想检查给定类型是否是该接口的实现.这种方法失败了

public class MyClass : MyInterface<int, string>
{
}
Run Code Online (Sandbox Code Playgroud)

但我不知道怎么做检查.

public void CheckIfTypeImplementsInterface(Type type)
{
    var result1 = typeof(MyInterface<,>).IsAssignableFrom(type); --> false
    var result2 = typeof(MyInterface<int,string>).IsAssignableFrom(type); --> true
}
Run Code Online (Sandbox Code Playgroud)

为了使result1真实,我该怎么做?

Lee*_*Lee 45

据我所知,唯一的方法是获取所有接口,看看通用定义是否与所需的接口类型匹配.

bool result1 = type.GetInterfaces()
    .Where(i => i.IsGenericType)
    .Select(i => i.GetGenericTypeDefinition())
    .Contains(typeof(MyInterface<,>));
Run Code Online (Sandbox Code Playgroud)

编辑:正如乔恩在评论中指出的那样,你也可以这样做:

bool result1 = type.GetInterfaces()
    .Where(i => i.IsGenericType)
    .Any(i => i.GetGenericTypeDefinition() == typeof(MyInterface<,>));
Run Code Online (Sandbox Code Playgroud)

  • 您可以将最后两个更改为:.Any(i => i.GetGenericTypeDefinition()== typeof(MyInterface <,>))` (5认同)
  • 您可以进一步简化为一个 lambda,使用`.Any(i =&gt; i.IsGenericType &amp;&amp; i.GetGenericTypeDefinition() == typeof(MyInterface&lt;,&gt;))`(不需要`.Where`,因为`.Any ` 已经在过滤项目) (2认同)