using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace EasyBL.DllDynamicCall { public class DllCall { private Assembly _assembly; public Dictionary Objects { get; set; } public Dictionary> Methods { get; set; } /// /// 构造器 /// /// DLL绝对路径 public DllCall(string dllPath) { LoadDll(dllPath); Objects = new Dictionary(); Methods = new Dictionary>(); } #region 公开方法 /// /// 注册要目标类 /// /// 类的完全限定名 /// 指定的对象名 /// 构造器参数类型 /// 构造器参数 public void RegisterObject(string classFullName, string objectName, Type[] constructorParaTypes, object[] constructorParas) { var t = _assembly.GetType(classFullName, true, false); var constructorInfo = t.GetConstructor(constructorParaTypes); if (constructorInfo != null) { var targetObject = constructorInfo.Invoke(constructorParas); if (!Objects.ContainsKey(objectName)) { Objects.Add(objectName, targetObject); } if (!Methods.ContainsKey(objectName)) { Methods.Add(objectName, new Dictionary()); } } } /// /// 注册函数 /// /// 类完全限定名 /// 制定函数所在对象名 /// 函数名 public void RegisterFunc(string classFullName, string objectName, string funcName) { var t = _assembly.GetType(classFullName, true, false); var method = t.GetMethod(funcName); if (Methods.ContainsKey(objectName)) { if (!Methods[objectName].ContainsKey(funcName)) { Methods[objectName].Add(funcName, method); } } } /// /// 调用函数 /// /// 目标对象名 /// 函数名 /// 参数表,没有参数则用null /// public object CallFunc(string objectName, string funcName, object[] paras) { var targetObjec = Methods[objectName]; var targetFunc = targetObjec[funcName]; const BindingFlags flag = BindingFlags.Public | BindingFlags.Instance; var result = targetFunc.Invoke(Objects[objectName], flag, Type.DefaultBinder, paras, null); return result; } #endregion 公开方法 #region 私有方法 /// /// 加载DLL /// /// DLL绝对路径 private void LoadDll(string dllPath) { if (File.Exists(dllPath)) { _assembly = Assembly.LoadFrom(dllPath); } else { throw new FileNotFoundException($"{dllPath} isn't exist!"); } } #endregion 私有方法 } }