猿问

如何确定类型是否实现特定的通用接口类型

假定以下类型定义:


public interface IFoo<T> : IBar<T> {}

public class Foo<T> : IFoo<T> {}

当只有整齐的类型可用时,如何确定该类型是否Foo实现了通用接口IBar<T>?


开满天机
浏览 513回答 3
3回答

HUH函数

通过使用TcK的答案,也可以使用以下LINQ查询来完成:bool isBar = foo.GetType().GetInterfaces().Any(x =>&nbsp; x.IsGenericType &&&nbsp; x.GetGenericTypeDefinition() == typeof(IBar<>));

斯蒂芬大帝

您必须遍历继承树,并在树中找到每个类的所有接口,如果接口是通用的,则与typeof(IBar<>)调用结果进行比较。当然,这有点痛苦。Type.GetGenericTypeDefinition

噜噜哒

public interface IFoo<T> : IBar<T> {}public class Foo : IFoo<Foo> {}var implementedInterfaces = typeof( Foo ).GetInterfaces();foreach( var interfaceType in implementedInterfaces ) {&nbsp; &nbsp; if ( false == interfaceType.IsGeneric ) { continue; }&nbsp; &nbsp; var genericType = interfaceType.GetGenericTypeDefinition();&nbsp; &nbsp; if ( genericType == typeof( IFoo<> ) ) {&nbsp; &nbsp; &nbsp; &nbsp; // do something !&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答