首頁  >  文章  >  後端開發  >  C# 動態載入Dll

C# 動態載入Dll

黄舟
黄舟原創
2017-02-18 10:52:341261瀏覽

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的!

 以上就是C#  動態載入Dll的內容,更多相關內容請關注PHP中文網(www.php.cn)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn