【问题标题】:Extracting list of types using reflection使用反射提取类型列表
【发布时间】:2021-09-24 08:26:57
【问题描述】:

我正在尝试编写一个应用程序来加载程序集并列出它再次依赖的程序集。这部分使用 Assembly.LoadFrom(asmPath) 和 GetReferencedAssemblies() 可以正常工作。

我还想从 dll 中提取一些公共信息。 主要是我想找到实现某些标签(通常是 Microsoft.AspNetCore.Mvc.ApiControllerAttribute)的类以及这些函数具有的参数。 当我尝试调用 asm.GetTypes() 时,我收到 ReflectionTypeLoadException,因为 Microsoft.AspNetCore.Mvc.Core 未加载。

有没有办法使用引用的程序集加载 Microsoft.AspNetCore.Mvc.Core?我正在尝试对很多 dll 执行此操作,因此无法在我的“程序集检查程序”中为所有引用添加 nuget 引用。或者有没有更好的方法来获取我正在寻找的信息?

【问题讨论】:

  • 你可能很幸运能够逃脱 Assembly.Load(AssemblyName) 即强制应用程序从目录加载程序集,尽管这充满了问题。
  • 给出同样的错误
  • 前提还是一样,你反映的dll依赖于程序集,这些程序集可以位于任何地方,但通常(不总是)在原始程序集所在的目录中) ,如果您可以加载所需的程序集,问题应该会消失...您是否检查过 Microsoft.AspNetCore.Mvc.Core 在加载后实际上已加载?
  • Microsoft.AspNetCore.Mvc.Core 不在文件夹中,它被编译到 dll 中或以不同的方式引用

标签: c# reflection


【解决方案1】:

下面是一段代码,我用它来查找实现一些通用接口的类型:

public static IEnumerable<ImplementedInterface> FindTypesImplementingGenericInterface(this Assembly assembly, Type genericInterfaceType)
    {
        var types = from type in assembly.GetTypes()
                    from iface in type.GetInterfaces()
                    where iface.IsGenericInterface(genericInterfaceType)
                    select new ImplementedInterface { Implementation = type, Interface = iface };
        return types;
    }

    public static bool IsGenericInterface(this Type type, Type genericInterfaceType)
    {
        return type.IsGenericType && type.GetGenericTypeDefinition() == genericInterfaceType;
    }

还有另一个片段,但用于从一个程序集中找到实现另一个程序集接口的类:

public static IEnumerable<dynamic> FindTypesImplementingInterface(Type impl_interface)
    {
        var interfaceAssembly = typeof(Contract.IEventWithTopic).Assembly;
        var implementationAssembly = typeof(Handlers.SmartTube.STAccountEventHandler).Assembly;

        var result = from @interface in interfaceAssembly.GetTypes()
                  from implementation in implementationAssembly.GetTypes()
                  where @interface.GetInterfaces().Any(i => i.Equals(impl_interface)) &&
                  implementation.GetInterfaces().Any(i => i.Equals(@interface))
                  select new { Interface = @interface, Implementation = implementation };

        return result;
    }

返回类型是动态的,因为没有类来存储数据。 您可以创建一个单独的类来存储这些结果或使用元组。

您可以尝试用属性替换接口,该方法应该可以正常工作。

以及这些函数的参数

GetMethods() 获取当前类型拥有的所有功能。 GetParameters() 获取当前方法(MethodInfo)拥有的所有参数信息。

【讨论】:

  • 谢谢,但如上所述,问题是 GetTypes() 崩溃,因为某些引用没有解决
猜你喜欢
  • 1970-01-01
  • 2012-04-03
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 2018-09-13
  • 2016-03-15
相关资源
最近更新 更多