假设以下类型定义:
public interface IFoo: IBar {} public class Foo : IFoo {}
当只有受损的类型可用时,如何确定类型是否Foo
实现了通用接口IBar
?
通过使用TcKs的答案,它也可以使用以下LINQ查询完成:
bool isBar = foo.GetType().GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IBar<>));
你必须通过继承树上去,找到树中的每个类的所有接口,并比较typeof(IBar<>)
与调用的结果Type.GetGenericTypeDefinition
,如果该接口是通用的.当然,这有点痛苦.
有关更多信息和代码,请参阅此答案和这些答案.
public interface IFoo: IBar {} public class Foo : IFoo {} var implementedInterfaces = typeof( Foo ).GetInterfaces(); foreach( var interfaceType in implementedInterfaces ) { if ( false == interfaceType.IsGeneric ) { continue; } var genericType = interfaceType.GetGenericTypeDefinition(); if ( genericType == typeof( IFoo<> ) ) { // do something ! break; } }
作为辅助方法的扩展
public static bool Implements(this Type type, I @interface) where I : class { if(((@interface as Type)==null) || !(@interface as Type).IsInterface) throw new ArgumentException("Only interfaces can be 'implemented'."); return (@interface as Type).IsAssignableFrom(type); }
用法示例:
var testObject = new Dictionary(); result = testObject.GetType().Implements(typeof(IDictionary )); // true!
我使用的是@GenericProgrammers扩展方法的简化版本:
public static bool Implements(this Type type) where TInterface : class { var interfaceType = typeof(TInterface); if (!interfaceType.IsInterface) throw new InvalidOperationException("Only interfaces can be implemented."); return (interfaceType.IsAssignableFrom(type)); }
用法:
if (!featureType.Implements()) throw new InvalidCastException();