本文共 1860 字,大约阅读时间需要 6 分钟。
在C#中,通过反射操作已加载的程序集中的类型和方法,可以实现隔空操作。以下是关于使用反射从外部DLL获取信息并调用方法的步骤指南:
首先,创建一个新的C#项目,选择“空项目”模板,展开项目属性,确保“输出类型”设置为“类库”,这样可以避免生成控制台应用程序,防止缺少Main方法的问题。
在项目属性中,将“输出路径”设置为反射所需的目录,确保反射可以找到生成的DLL文件。
确保测试反射的下层项目(TestDll)已在bin/Debug目录下正确生成TestDll.dll文件。如果遇到生成问题,检查项目输出路径是否正确。
在反射使用的程序中,使用以下代码加载DLL并获取所需的类型。确保在代码中正确引用System.Reflection命名空间,或者在代码开头添加using System.Reflection;。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Reflection;namespace Reflection{ class Program { static void Main(string[] args) { // 加载所需的DLL文件 string assemblyPath = Environment.CurrentDirectory + "\\TestDll.dll"; Assembly loadedDll = Assembly.LoadFile(assemblyPath); try { // 获取类 Type mathType = loadedDll.GetType("TestDll.Math"); // 获取方法 MethodInfo addMethod = mathType.GetMethod("Add"); // 调用方法并处理结果 object result = addMethod.Invoke(new object[] {10, 20}); Console.WriteLine("Method result: " + result); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } finally { Console.WriteLine("Reflection completed."); } } }}
编写上述代码后,运行反射程序,查看输出结果是否正确调用了TestDll.Math.Add方法。如果出现错误,回头检查类名、命名空间和方法定义是否正确。
通过以上步骤,可以名 正确地反射外部类和方法,实现隔空取物的效果。记住,反射提供了一个灵活的解决方案,尤其是在需要动态获取类型信息或修改代码行为时非常有用。
转载地址:http://tpzzk.baihongyu.com/