Dynamic loading of DLL in C#
C# allows DLLs to be loaded and used dynamically at runtime. The Assembly.LoadFile()
method allows loading a DLL into an application.
Problem: Unable to use methods from a loaded DLL in a console application
Users reported being able to load the DLL but not being able to access its methods. This is because the C# compiler cannot pre-resolve types and members in the DLL. To call methods in a DLL, you need to use reflection or dynamic objects.
Solution 1: Use Reflection
Reflection allows obtaining type metadata and calling its members at runtime. Using reflection requires explicitly calling the method:
<code class="language-csharp">// 加载 DLL var assembly = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll"); // 遍历 DLL 中导出的类型 foreach (Type type in assembly.GetExportedTypes()) { // 创建类型实例 var instance = Activator.CreateInstance(type); // 调用方法 (假设方法名为 "Output" 并接受一个字符串参数) type.InvokeMember("Output", BindingFlags.InvokeMethod, null, instance, new object[] { "Hello" }); }</code>
Solution 2: Use dynamic objects (.NET 4.0 and above)
Dynamic objects allow calling DLL methods in code without explicit type conversion and with a simpler syntax:
<code class="language-csharp">// 加载 DLL var assembly = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll"); // 遍历 DLL 中导出的类型 foreach (Type type in assembly.GetExportedTypes()) { // 创建动态实例 dynamic instance = Activator.CreateInstance(type); // 调用方法 (假设方法名为 "Output" 并接受一个字符串参数) instance.Output("Hello"); }</code>
Both solutions show how to dynamically access methods in a DLL. Which method you choose depends on your .NET version and personal preference. Reflection provides finer control, while dynamic objects simplify code. Note that @"C:visual studio 2012ProjectsConsoleApplication1ConsoleApplication1DLL.dll"
needs to be replaced with the actual path to your DLL.
The above is the detailed content of How Can I Access Methods Within a Dynamically Loaded DLL in a C# Console Application?. For more information, please follow other related articles on the PHP Chinese website!