C# - 加载 DLL 动态 - System.Reflection.ReflectionTypeLoadException: 无法加载一种或多种请求的类型

C# - Loading DLL Dynamic - System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types

在 C# 中,当使用以下代码从文件夹加载 DLL 时,在尝试获取类型时获取这些堆栈跟踪。

var assembly = Assembly.LoadFile(assemblyInfo.FullName); // assembly loads perfectly using the absolute path.
var types = assembly.GetTypes(); // this line throws the below stacktrace.

堆栈跟踪:

System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.Assembly.GetTypes()

我也检查了现有的解决方案:Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.', Loading DLLs at runtime in C#(没有用)

问题的解决很简单。它只是使用了与程序集不同的方法。我们应该使用 LoadFrom

而不是 LoadFile

所以下面的代码有效的解决了这个问题

var assembly = Assembly.LoadFrom(assemblyInfo.FullName); // loads perfectly, absolute path to dll
var types = assembly.GetTypes(); // loads perfectly.

无需使用 GetExportedTypes。我们可以得到所有的类型。

LoadFrom 会与其他 DLL 进行自动反射绑定,但是 loadfile 不会这样做。

这解决了导出问题。

Assembly.LoadFile 只加载 contents of an assembly ,但是 Assembly.LoadFrom 完美加载 assembly file (如果有依赖项)。