1.定义DLL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClassLibrary1
{
    public class ClassGreenerycn
    {
        public string Name { get; set; }

        public bool IsTest { get; set; }

        public void Hello()
        {
            if (IsTest)
            {
                MessageBox.Show(Name);
            }
            else
            {
                MessageBox.Show("IsTest=true时;才显示对应的Name!!!");
            }
        }
    }
}

2.反射调用DLL

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;//1.引用反射的命名空间:

namespace WindowsFormsApplication1
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //2.动态加载Dll
            var asm = Assembly.LoadFile(@"F:\TEST程序\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\ClassLibrary1.dll");
            //3.获取ClassGreenerycn类的类型(注意,这里需要完整的类型名称,包括签名的命名空间。)
            var type = asm.GetType("ClassLibrary1.ClassGreenerycn");
            //4.创建该类型的实例
            var instance = asm.CreateInstance("ClassLibrary1.ClassGreenerycn");
            //5.设置属性
            type.GetProperty("Name").SetValue(instance, "http://greenerycn.cnblogs.com", null);
            type.GetProperty("IsTest").SetValue(instance, true, null);
            //6.获取Hello方法
            var method = type.GetMethod("Hello");
            //7.调用Hello方法
            method.Invoke(instance, null);
        }
    }
}

 

注意:

动态加载Dll有3个函数:

public static Assembly Load(string assemblyString);
  • 该方法传入的是Dll的名字,该Dll必须位于全局缓存GAC中才行,不然会报“System.IO.FileLoadException: 未能加载文件或程序集”的异常。
public static Assembly LoadFile(string path);
  • 这个LoadFile最方便,参数就是dll的路径。
public static Assembly LoadFrom(string assemblyFile);
  • 这个方法也可以,参数同样是dll路径。

 

posted on 2015-10-09 15:25  清风暮雨  阅读(152)  评论(0)    收藏  举报