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设计,毕竟他破坏了类的封装性。

转载于:https://www.cnblogs.com/linuxjava01/p/3729831.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值