[英]Check if a Type derives from a Interface with more than one Generic Argument
我有一個關於使用反射加載類型的問題。 我試圖通過實現具有兩個泛型參數的接口的那些來過濾程序集中的類型列表。 我不打算明確說明哪些類型是那些泛型參數,因為我想要所有實現接口的類,但是每當我嘗試使用typeof(IExample<>)
時,它都會被標記為錯誤。 但是,可以使用只有一個通用參數的接口來做到這一點。 我真的很感激一些幫助:提前謝謝:)
public interface IExample<T, E>
{
}
這就是我的界面的樣子。 然后我目前必須實現它的類。
public class C
{
}
public class A : IExample<string, C>
{
}
Public class B : IExample<XMLDocument, C>
{
}
您與我可以從您的問題中檢查的內容相差不遠。 為了獲得正確的泛型類型,沒有任何泛型 arguments 您需要調用typeof(IExample<,>)
,注意有一個逗號!
對於您關於如何獲取這些類型的問題的另一部分,您可以執行以下操作:
public static IEnumerable<Type> GetTypesWithGenericArguments(Assembly assembly, Type implementingInterface)
{
var types = assembly.GetTypes();
// Loop over all Types in the assembly
foreach (var type in types)
{
// Skipping all Types which aren't classes
if (!type.IsClass)
continue;
var implementedInterfaces = type.GetInterfaces();
// Loop over all interfaces the type implements
foreach (var implementedInterface in implementedInterfaces)
{
// Return the type if it one of its interfaces are matching the implementingInterface
if (implementedInterface.IsGenericType && implementedInterface.GetGenericTypeDefinition() == implementingInterface)
{
yield return type;
// You can leave the loop, since you don't need to check the other
// interfaces, since you already found the one you were searching for.
break;
}
}
}
}
可以這樣使用:
public static void Main(string[] args)
{
foreach (var item in GetTypesWithGenericArguments(Assembly.GetCallingAssembly(), typeof(IExample<,>)))
{
Console.WriteLine(item.Name);
}
// This would print to the Console:
// A
// B
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.