通过Reflection实现接口

39 c# reflection interface

如何通过C#中的反射获得接口的所有实现?

Ste*_*per 58

答案是这样的; 它搜索整个应用程序域 - 即应用程序当前加载的每个程序集.

/// <summary>
/// Returns all types in the current AppDomain implementing the interface or inheriting the type. 
/// </summary>
public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
    return AppDomain
           .CurrentDomain
           .GetAssemblies()
           .SelectMany(assembly => assembly.GetTypes())
           .Where(type => desiredType.IsAssignableFrom(type));
}
Run Code Online (Sandbox Code Playgroud)

就像这样使用;

var disposableTypes =  TypesImplementingInterface(typeof(IDisposable));
Run Code Online (Sandbox Code Playgroud)

您可能还希望此函数查找实际的具体类型 - 即过滤掉摘要,接口和泛型类型定义.

public static bool IsRealClass(Type testType)
{
    return testType.IsAbstract == false
         && testType.IsGenericTypeDefinition == false
         && testType.IsInterface == false;
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,此代码无法看到未来 - 它无法在尚未加载的接口中找到此接口的实现. (8认同)

Ant*_*ton 5

看看Assembly.GetTypes()方法.它返回可在程序集中找到的所有类型.您所要做的就是遍历每个返回的类型并检查它是否实现了必要的接口.

在这样做的Type.IsAssignableFrom方法是使用方法.

这是一个例子.myInterface是您正在搜索的接口,实现.

Assembly myAssembly;
Type myInterface;
foreach (Type type in myAssembly.GetTypes())
{
    if (myInterface.IsAssignableFrom(type))
        Console.WriteLine(type.FullName);
}
Run Code Online (Sandbox Code Playgroud)

我确实认为这不是解决问题的有效方法,但至少,它是一个很好的起点.


Ale*_*eby 1

您的意思是 Type 实现的所有接口吗?

像这样:

ObjX foo = new ObjX();
Type tFoo = foo.GetType();
Type[] tFooInterfaces = tFoo.GetInterfaces();
foreach(Type tInterface in tFooInterfaces)
{
  // do something with it
}
Run Code Online (Sandbox Code Playgroud)

希望有帮助。