检查类型是否实现了泛型接口而不考虑泛型类型参数 [英] Check if a type implements a generic interface without considering the generic type arguments

查看:32
本文介绍了检查类型是否实现了泛型接口而不考虑泛型类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个界面

public interface MyInterface<TKey, TValue>
{
}

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

Implementations are irrelevant. Now I want to check if a given type is an implementation of that interface. This method fails for

public class MyClass : MyInterface<int, string>
{
}

但我不知道如何进行检查.

But I don't know how to do the check.

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

我需要做什么才能使 result1 为真?

What do I have to do for result1 to be true?

推荐答案

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

As far as I know, the only way to do this is to get all interfaces and see if the generic definition matches the required interface type.

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

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

As Jon points out in the comments, you could also do:

bool result1 = type.GetInterfaces()
    .Where(i => i.IsGenericType)
    .Any(i => i.GetGenericTypeDefinition() == typeof(MyInterface<,>));

这篇关于检查类型是否实现了泛型接口而不考虑泛型类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆