我有一个界面
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/