C# 动态载入Dll

1、新建測试dll及方法,用vs2010新建winform程序,详细代码例如以下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace reflect
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public string TestReflect()
        {
            MessageBox.Show("动态载入Dll測试");
            return "TestReflect返回值";
        }
    }
}
2、动态载入代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace reflectTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //载入dll中的函数
            //Assembly asm = Assembly.Load(strDllPath);//载入当前根文件夹的dll
            Assembly asm = Assembly.LoadFile(@"F:\WorkSpace\VS測试代码\反射測试001\反射message方法\reflect\reflect\bin\Debug\reflect.dll");//依据dll文件实际路径载入
            //用类型的命名空间和类获得类型
            System.Type FromClass = asm.GetType("reflect.Form1");
            //须要实例化类型,才干够使用,參数能够人为的指定,也能够无參数,静态实例能够省略
            Object obj = System.Activator.CreateInstance(FromClass);
            //通过方法名称获得方法(调试走到以下这一步的时候,就能够弹出“动态载入Dll測试”这个消息了)
            MethodInfo method = FromClass.GetMethod("TestReflect");
            //获取TestReflect函数的返回值,在这里会获取到"TestReflect返回值",假设没有返回值,能够省略这一步
            object o = method.Invoke(obj, new object[] { });
        }
    }
}
小注:

通过方法名称获得方法中的方法必须是public的!



posted @ 2014-10-30 18:43  zfyouxi  阅读(303)  评论(0编辑  收藏  举报