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