我該如何反思在.NET中給定類型(類或接口)實現的接口?在C中的類型接口反映出來#
由於被反映的類型將是泛型的(無論是在實現意義還是語義意義上),最好在不必硬編碼程序集名稱的情況下執行此操作,但我意識到可以獲取該名稱來自任何給定類型的Type類。
我該如何反思在.NET中給定類型(類或接口)實現的接口?在C中的類型接口反映出來#
由於被反映的類型將是泛型的(無論是在實現意義還是語義意義上),最好在不必硬編碼程序集名稱的情況下執行此操作,但我意識到可以獲取該名稱來自任何給定類型的Type類。
調用Type.GetInterfaces()。
Type.GetInterfaces()只能得到你聲明接口(MSDN應該有解釋這個的文檔)。要獲得繼承的接口,你必須自己完成工作。東西類似到:
using System;
using System.Linq;
public static IEnumerable<Type> GetAllInterfacesForType(this Type type)
{
foreach (var interfaceType in type.GetInterfaces())
{
yield return interfaceType;
foreach (var t in interfaceType.GetAllInterfacesForType())
yield return t;
}
}
public static IEnumerable<Type> GetUniqueInterfacesForType(this Type type)
{ return type.GetAllInterfaces().Distinct(); }
我寫這篇即興很抱歉,如果它不編譯直失控達盒。
我不認爲這是正確的。從MSDN返回的GetInterfaces()是: 類型:array
現在這太簡單了;)謝謝。 – johnc 2009-04-18 05:21:28