閱讀901 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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



最後更新:2017-04-03 16:49:26

  上一篇:go 機房收費係統之思想性總結
  下一篇:go .NET中IO體係結構