C#运用反射调用其他程序集中的代码
加载程序集
AssMedicalAdvice = Assembly.LoadFrom(Path.Combine(Environment.CurrentDirectory, "Inscription.MedicalAdvice.Client.dll"));
1.调用静态函数,静态函数不需要实例化类,所以methodInfo.Invoke第一个参数为null
type = AssClinicalPaths.GetType("Inscription.ClinicalPaths.Client.CommonCtl.RasonV2.CP_RASON_GridFormV2"); methodInfo = type.GetMethod("Test"); methodInfo.Invoke(null, new string[] { });
2.获取静态属性
type = AssClinicalLib.GetType("Inscription.ClinicalPaths.Lib.LibManager"); string strDbType = type.GetProperty("strDBType").GetValue(null, null).ToString(); string strDbConn = type.GetProperty("strDBConn").GetValue(null, null).ToString();
3.获取实例属性
type = AssMedicalLib.GetType("Inscription.MedicalAdvice.Object.BaseSreverManager"); object objBaseServerManager = type.GetProperty("sBaseSreverManager").GetValue(null, null); strDbType = type.GetProperty("DBType").GetValue(objBaseServerManager, null).ToString(); strDbConn = type.GetProperty("DBConn").GetValue(objBaseServerManager, null).ToString();
4.调用非静态函数,需要获取PathManager类的实例化。
或者使用Activator.CreateInstance(type)实例化类
type = AssClinicalPaths.GetType("Inscription.ClinicalPaths.Lib.PathManager");
//Object objPathManager = Activator.CreateInstance(type); Object objPathManager = type.GetProperty("pathManager").GetValue(null, null); methodInfo = type.GetMethod("in_RunTimeObject"); methodInfo.Invoke(objPathManager, new string[] { });
PS:反射有个有趣的特性,就是能够访问私有的字段,属性和方法。
有点类似代码级别的Hack行为。不知道这算不算一个好的OO设计,毕竟他破坏了类的封装性。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步