反射机制访问程序集例子(自己写的小例子作参考)

知道程序集中的方法名称,通过反射使用程序集中的方法!

先建立一个类库(此类库作为程序集用来加载)

在建好的类库中写入方法

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace test
{
    public class Class1
    {
        public string WriteString(string s)
        {
            return "欢迎您," + s;
        }
        
        public static string WriteName(string s)
        {
            return "欢迎您光临," + s;
        }

        public string WriteNoPara()
        {
            return "您使用的是无参数方法";
        }
    }
}


然后生成解决方案。此时在该类库的解决方案的位置的E:\..代码\TEST\程序集反射\test\bin\Debug下生成文件test.dll,将该文件放到合适的位置用于加载程序集。(我将它拷贝到E盘根目录下)

此时再建立窗体应用程序UseReflection

Form1窗体代码如下:(知道程序集中的方法名称,通过方法名定义并使用方法)

View Code
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 UseReflection1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            test1();//程序集的反射
        }
        #region
        /// <summary>
        /// 程序集的反射
        /// </summary>
        public void test1()
        {
            Assembly ass;
            Type type;
            object obj;
            try
            {
                ass = System.Reflection.Assembly.LoadFile(@"e:\test.dll");
                type = ass.GetType("test.Class1");//必须使用名称空间+类名称
                System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法的名称
                obj = ass.CreateInstance("test.Class1");//必须使用名称空间+类名称
                string s = (string)method.Invoke(obj, new string[] { "jianglijun" }); //实例方法的调用
                label1.Text = s;

                method = type.GetMethod("WriteName");//方法的名称
                s = (string)method.Invoke(null, new string[] { "jianglijun" }); //静态方法的调用
                label2.Text = s;

                method = type.GetMethod("WriteNoPara");//无参数的实例方法
                s = (string)method.Invoke(obj, null);
                label3.Text = s;

                method = null;
            }
            catch (Exception ex)
            {
                label1.Text = ex.ToString();
            }
            finally
            {
                ass = null;
                type = null;
                obj = null;
            }
        }
        #endregion
    }
}

 结果如下:

 

posted @ 2013-04-03 10:21  sevennight99  阅读(207)  评论(0编辑  收藏  举报