为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

开满天机 2019-11-25 13:21:37
假定以下类型定义:public interface IFoo<T> : IBar<T> {}public class Foo<T> : IFoo<T> {}当只有整齐的类型可用时,如何确定该类型是否Foo实现了通用接口IBar<T>?
查看完整描述

3 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

通过使用TcK的答案,也可以使用以下LINQ查询来完成:


bool isBar = foo.GetType().GetInterfaces().Any(x =>

  x.IsGenericType &&

  x.GetGenericTypeDefinition() == typeof(IBar<>));


查看完整回答
反对 回复 2019-11-25
?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

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

查看完整回答
反对 回复 2019-11-25
?
噜噜哒

TA贡献1784条经验 获得超7个赞

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

public class Foo : IFoo<Foo> {}


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;

    }

}


查看完整回答
反对 回复 2019-11-25
  • 3 回答
  • 0 关注
  • 472 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信