开发语言:C#
源码大小:39KB
源码大小:39KB
视频教程,进入B站可以看高清视频
1. 创建一个简单的DLL
首先,假设你有一个简单的C#类库项目,生成一个DLL文件。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace test { public class Calculator { public int Add( int a, int b) { return a + b; } public int Subtract( int a, int b) { return a - b; } } } |
编译这个项目后,你会得到一个test.dll文件。
2. 动态加载并调用DLL中的方法
接下来,你可以在另一个C#项目中动态加载这个DLL并调用其中的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace ConsoleApp1 { class Program { static void Main( string [] args) { // 加载DLL Assembly assembly = Assembly.LoadFrom( "test.dll" ); // 获取类型 Type calculatorType = assembly.GetType( "test.Calculator" ); // 创建实例 object calculatorInstance = Activator.CreateInstance(calculatorType); // 获取方法信息 MethodInfo addMethod = calculatorType.GetMethod( "Add" ); // 调用方法 object [] parameters = new object [] { 5, 3 }; int result = ( int )addMethod.Invoke(calculatorInstance, parameters); Console.WriteLine( "5 + 3 = " + result); // 调用另一个方法 MethodInfo subtractMethod = calculatorType.GetMethod( "Subtract" ); int subtractResult = ( int )subtractMethod.Invoke(calculatorInstance, new object [] { 5, 3 }); Console.WriteLine( "5 - 3 = " + subtractResult); Console.ReadKey(); } } } |
3. 运行程序
确保test.dll文件位于与可执行文件相同的目录中,或者提供正确的路径。运行程序后,你会看到以下输出:
1 2 | 5 + 3 = 8 5 - 3 = 2 |
4. 注意事项
路径问题:确保DLL文件位于正确的路径,或者使用绝对路径来加载DLL。
异常处理:在实际应用中,建议添加异常处理来捕获可能出现的错误,例如文件未找到、类型未找到、方法未找到等。
性能:反射调用比直接调用方法要慢,因此在性能敏感的场景中应谨慎使用。
5. 使用dynamic关键字(可选)
如果你使用的是C# 4.0或更高版本,可以使用dynamic关键字来简化代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace ConsoleApp1 { class Program { static void Main( string [] args) { // 加载DLL Assembly assembly = Assembly.LoadFrom( "test.dll" ); // 获取类型 Type calculatorType = assembly.GetType( "test.Calculator" ); // 创建实例 dynamic calculatorInstance = Activator.CreateInstance(calculatorType); // 调用方法 int result = calculatorInstance.Add(5, 3); Console.WriteLine( "5 + 3 = " + result); // 调用另一个方法 int subtractResult = calculatorInstance.Subtract(5, 3); Console.WriteLine( "5 - 3 = " + subtractResult); Console.ReadKey(); } } } |
使用dynamic关键字可以避免显式使用反射来调用方法,代码更加简洁。
总结
通过反射,你可以在运行时动态加载和调用C#编写的DLL中的方法。这种方法非常灵活,适用于插件系统、动态加载模块等场景。
本文来自 www.luofenming.com