请注意,如果您有一个通用接口 IMyInterface<T>,那么这将始终返回 false:
typeof(IMyInterface<>).IsAssignableFrom(typeof(MyType)) /* ALWAYS FALSE */
这也不起作用:
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface<>)) /* ALWAYS FALSE */
但是,如果MyType 实现IMyInterface<MyType>,这将起作用并返回true:
typeof(IMyInterface<MyType>).IsAssignableFrom(typeof(MyType))
但是,您可能在运行时不知道类型参数 T。一个有点 hacky 的解决方案是:
typeof(MyType).GetInterfaces()
.Any(x=>x.Name == typeof(IMyInterface<>).Name)
Jeff 的解决方案不那么老套:
typeof(MyType).GetInterfaces()
.Any(i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IMyInterface<>));
这是Type 上的一个扩展方法,适用于任何情况:
public static class TypeExtensions
{
public static bool IsImplementing(this Type type, Type someInterface)
{
return type.GetInterfaces()
.Any(i => i == someInterface
|| i.IsGenericType
&& i.GetGenericTypeDefinition() == someInterface);
}
}
(请注意,上面使用了 linq,这可能比循环慢。)
你可以这样做:
typeof(MyType).IsImplementing(IMyInterface<>)