代码改变世界

详解C#动态调用委托的DLL的方法

2010-09-23 11:31  xchit  阅读(757)  评论(0编辑  收藏  举报

   public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            object[] obj = new object[1];
            obj[0] = "DllInvoke";
            object o2 = DllInvoke("E:\\Test\\TestDll\\bin\\Debug\\TestDll.dll", "TestDll", "TestDll", "HandleStr", obj);
            MessageBox.Show(o2.ToString());
        }

        /// <summary>
        /// 动态调用DLL
        /// </summary>
        /// <param name="DllFileName">dll名称</param>
        /// <param name="NameSpace">命名空间</param>
        /// <param name="ClassName">类名</param>
        /// <param name="MethodName">方法名</param>
        /// <param name="ObjArrayParams">参数数组</param>
        /// <returns></returns>
        private object DllInvoke(string DllFileName, string NameSpace, string ClassName, string MethodName, object[] ObjArrayParams)
        {
            try
            {
                //载入程序集
                Assembly DllAssembly = Assembly.LoadFrom(DllFileName);
                Type[] DllTypes = DllAssembly.GetTypes();
                foreach (Type DllType in DllTypes)
                {
                    //查找要调用的命名空间及类
                    if (DllType.Namespace == NameSpace && DllType.Name == ClassName)
                    {
                        //查找要调用的方法并进行调用
                        MethodInfo MyMethod = DllType.GetMethod(MethodName);
                        if (MyMethod != null)
                        {
                            object mObject = Activator.CreateInstance(DllType);
                            return MyMethod.Invoke(mObject, ObjArrayParams);
                        }
                    }
                }
            }
            catch (Exception mEx)
            {
                throw new Exception(mEx.Message);
            }
            return (object)0;
        }
    }