在C#开发中,有时我们需要在程序运行时动态加载外部程序集(DLL文件),并调用其中的类或方法。这种能力被称为动态程序集加载,广泛应用于插件系统、热更新、模块化架构等场景。本教程将手把手教你如何使用C#实现动态程序集加载和反射执行代码,即使你是编程新手也能轻松上手。
在传统的C#项目中,我们通过添加引用(Reference)来使用其他DLL中的功能。这种方式在编译时就确定了依赖关系。而动态程序集加载允许我们在程序运行期间,根据需要加载指定的DLL文件,并通过.NET反射机制调用其中的类型和方法。
你需要:
首先,我们创建一个简单的类库项目,用于生成DLL。
MyPluginClass1.cs 中写入以下代码:namespace MyPlugin{ public class Calculator { public int Add(int a, int b) { return a + b; } public string GetMessage() { return "Hello from dynamic assembly!"; } }} 编译该项目,你会在输出目录(如 bin\Debug\net6.0)中得到 MyPlugin.dll 文件。
现在,我们创建一个控制台应用程序,用于动态加载上面生成的DLL。
using System;using System.IO;using System.Reflection;class Program{ static void Main(string[] args) { // 指定DLL的路径 string dllPath = @"C:\path\to\your\MyPlugin.dll"; if (!File.Exists(dllPath)) { Console.WriteLine("DLL文件不存在!"); return; } // 动态加载程序集 Assembly assembly = Assembly.LoadFrom(dllPath); // 获取类型 Type? calcType = assembly.GetType("MyPlugin.Calculator"); if (calcType == null) { Console.WriteLine("未找到指定类型!"); return; } // 创建实例 object? instance = Activator.CreateInstance(calcType); if (instance == null) { Console.WriteLine("无法创建实例!"); return; } // 调用方法 MethodInfo? addMethod = calcType.GetMethod("Add"); if (addMethod != null) { object result = addMethod.Invoke(instance, new object[] { 10, 20 }); Console.WriteLine($"Add(10, 20) = {result}"); } MethodInfo? getMessageMethod = calcType.GetMethod("GetMessage"); if (getMessageMethod != null) { object message = getMessageMethod.Invoke(instance, null); Console.WriteLine($"Message: {message}"); } }} 这段代码展示了完整的C#动态程序集加载流程:
Assembly.LoadFrom() 加载DLLGetType() 获取目标类型Activator.CreateInstance() 创建对象实例GetMethod() 和 Invoke() 调用方法Path.Combine 构建路径。FileNotFoundException、ReflectionTypeLoadException 等异常。除了加载已有DLL,你还可以在运行时动态编译C#源代码。这需要用到 Microsoft.CodeAnalysis.CSharp(Roslyn编译器)。这是.NET动态编译的高级应用,适合构建脚本引擎或规则引擎。
通过本教程,你已经掌握了如何在C#中实现动态程序集加载、反射执行代码,以及如何构建灵活的插件式架构。这些技术是实现C#运行时加载DLL和.NET动态编译的基础。希望你能将这些知识应用到实际项目中,提升程序的灵活性和可扩展性!
提示:记得将示例中的DLL路径替换为你本地的实际路径哦!
本文由主机测评网于2025-12-07发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025124130.html