检查一个类型实现一个通用接口不考虑泛型类型参数 [英] Check if a type implements a generic interface without considering the generic type arguments

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

问题描述

我有一个接口

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天全站免登陆