博客
关于我
隔空取物——reflection
阅读量:759 次
发布时间:2019-03-23

本文共 1860 字,大约阅读时间需要 6 分钟。

在C#中,通过反射操作已加载的程序集中的类型和方法,可以实现隔空操作。以下是关于使用反射从外部DLL获取信息并调用方法的步骤指南:

1. 创建项目

首先,创建一个新的C#项目,选择“空项目”模板,展开项目属性,确保“输出类型”设置为“类库”,这样可以避免生成控制台应用程序,防止缺少Main方法的问题。

2. 设置输出路径

在项目属性中,将“输出路径”设置为反射所需的目录,确保反射可以找到生成的DLL文件。

3. 预先准备DLL文件

确保测试反射的下层项目(TestDll)已在bin/Debug目录下正确生成TestDll.dll文件。如果遇到生成问题,检查项目输出路径是否正确。

4. 配置反射代码

在反射使用的程序中,使用以下代码加载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.");            }        }    }}

5. 注意事项和误区

  • 命名空间配置:确保TestDll项目的命名空间设置正确,否则反射无法找到TestDll.Math类。可以在项目的Properties中找到AnnealingSupported的快捷键设置,确保全名的正确性。
  • 大写问题:类名TestDll.Math的首字母是否大写会影响反射结果。在代码中使用 GetType("TestDll.Math")而不是GetType("testDll.math")。
  • 权限检查:如果反射从本外部加载DLL,确保 Odibi集中的类和方法的访问权限正确。有时可能需要在代码中加入反射权限 року//"反射权限。

6. 测试反射结果

编写上述代码后,运行反射程序,查看输出结果是否正确调用了TestDll.Math.Add方法。如果出现错误,回头检查类名、命名空间和方法定义是否正确。

通过以上步骤,可以名 正确地反射外部类和方法,实现隔空取物的效果。记住,反射提供了一个灵活的解决方案,尤其是在需要动态获取类型信息或修改代码行为时非常有用。

转载地址:http://tpzzk.baihongyu.com/

你可能感兴趣的文章
Pinia:$subscribe()的使用场景
查看>>
Pinpoint对Kubernetes关键业务模块进行全链路监控
查看>>
Pinterest 大规模缓存集群的架构剖析
查看>>
pintos project (2) Project 1 Thread -Mission 1 Code
查看>>
PinYin4j库的使用
查看>>
PIP
查看>>
pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
查看>>
pip install mysqlclient报错
查看>>
pip install 出现报asciii码错误的解决
查看>>
pip throws TypeError: parse() got an unexpected keyword argument ‘transport_encoding‘ 在尝试安装新软件包时
查看>>
pip 下载慢
查看>>
pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
查看>>
pip 安装opencv-python卡死
查看>>
pip 安装出现异常
查看>>
Pip 安装失败:需要 SSL
查看>>
Pip 安装挂起
查看>>
pip 或 pip3 为 Python 3 安装包?
查看>>
pip 文件损坏导致 pip无法使用 报错 ImportError: cannot import name 'main' from 'pip._int
查看>>
pip/pip3更换国内源
查看>>
pip3 install PyQt5 --user 失败
查看>>