亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何確定類型是否實現特定的通用接口類型

如何確定類型是否實現特定的通用接口類型

開滿天機 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 關注
  • 532 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號