c# - 在不考虑泛型类型参数的情况下检查类型是否实现了泛型接口(interface)

标签 c# generics types interface

我有一个界面

public interface MyInterface<TKey, TValue>
{
}

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

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

但是我不知道怎么检查。

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

我必须做什么才能使 result1 为真?

最佳答案

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

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

编辑:正如 Jon 在评论中指出的那样,您还可以:

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

关于c# - 在不考虑泛型类型参数的情况下检查类型是否实现了泛型接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18233390/

相关文章:

c# - 避免循环中的对象实例化 c# - 如何避免这种情况?

c# - 什么更好?枚举还是类型检查?

c# - 使用 Naudio 创建 Clapper 软件

java - 仅支持半开范围时如何进行包含范围查询(ala SortedMap.subMap)

arrays - 函数数组<可选<T>> -> 可选<数组<T>>

c# - 为什么参数化通用接口(interface)的 GetMethods() 返回非参数化 MethodInfo

C# 如何将函数调用保存在内存中供以后调用

haskell - 手动推断类型 (\x y z -> (x y) z)

c# - 从 RTF 文本中获取纯文本

c# - 如何对 ToolStripItem 集合中的项目进行排序?