利用.net反射動態調用指定程式集的中的方法

來源:互聯網
上載者:User
每個.net程式集除了代碼外都額外包含了中繼資料。中繼資料套件括了程式集本身的資訊,比如版本號碼,引用了什麼程式集,所有類型的資訊,包括其方法、屬性、欄位。使用.net反射,可以在運行時讀取這些資訊,並且可以動態地調用方法。
     項目快完了,終於有時間來寫blog了,,
     做一個動態調用程式集指定方法的例子。
     項目1(Demo)中包含一個Test類,Test類中寫了一個getList方法,這個方法返回的資料是手工加入的。原始碼如下:
      項目1
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Demo
{
    public class Test
    {
        public DataTable getList(string id)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("id"));
            dt.Columns.Add(new DataColumn("name"));
            dt.Columns.Add(new DataColumn("sex"));
            DataRow dr = dt.NewRow();
            dr["id"] = "zl";
            dr["name"] = "張鈴";
            dr["sex"] = "男";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["id"] = "zl";
            dr["name"] = "李四";
            dr["sex"] = "女";
            dt.Rows.Add(dr);
            return dt;
 }
    }
}

 

     項目2(DemoXml)中包含一個Test類,Test類中寫了一個getList方法,這個方法返回的資料是從資料庫讀取的。原始碼如下:
項目2
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
namespace DemoXml
{
    public class Test
    {
        private SqlConnection cn;
        public DataTable getList(string id)
        {
            try
            {
                cn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["pubs"]);
                SqlCommand cmd = new SqlCommand();
                SqlDataAdapter da = new SqlDataAdapter();
                cmd.CommandText = "SELECT au_id as id,au_lname as name,au_fname as sex from authors";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = cn;
                da.SelectCommand = cmd;
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
}
            catch (Exception ex)
            {
                throw new ApplicationException("出現異常:"+ex.Message+ex.StackTrace);
            }
            finally
            {
                cn.Close();
                cn = null;
            }
        }
    }
}

 

      項目3(WebDemo)中示範動態用指定程式集中getList的方法返回一個DataTable,用一個gridview顯示其返回的資料。
調用示範
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropBind();
        }
    }
    資料初始化,可配置在web.config檔案中#region 資料初始化,可配置在web.config檔案中
    public void DropBind()
    {
        DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("name"));
        dt.Columns.Add(new DataColumn("filepath"));
        DataRow dr = dt.NewRow();
        dr["name"] = "載入自己定義資料";
        dr["filepath"] = Server.MapPath(@"Files\Demo.dll");
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["name"] = "載入xml資料";
        dr["filepath"] = Server.MapPath(@"Files\DemoXml.dll");
        dt.Rows.Add(dr);
        this.DropDownList1.DataSource = dt;
        this.DropDownList1.DataTextField = "name";
        this.DropDownList1.DataValueField = "filepath";
        this.DropDownList1.DataBind();
    }
    #endregion

 

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            //讀取選擇指定的dll檔案
            string strPath = (sender as DropDownList).SelectedValue.Trim();
            string NameSpace = this.DropDownList1.SelectedIndex == 0 ? "Demo.Test" : "DemoXml.Test";
            //載入指定的程式集之記憶體中
            Assembly assembly = Assembly.LoadFrom(strPath);
            //返加程式集中的一個指定的對象,哪果是返回所有對象,則用GetTypes()返回一個Typt對象的數組.
Type T = assembly.GetType(NameSpace);
            //返回方法資訊(公用方法)
            MethodInfo mi = T.GetMethod("getList");
            //根據前面type類型建立一個對象
            object o = Activator.CreateInstance(T);
            //參數
            object[] par = new object[] { "E01" };
            //通過MethodInfo對象的Invoke方法,動態調用此方法,參數o是因為執行個體方法需要在調用時有一個執行個體存在
            DataTable dt = (DataTable)mi.Invoke(o, par);
            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
        }
        catch (Exception ex)
        {
            //do Exception
        }
    }
}

 

       通過Assembly.LoadFrom方法返回的Assembly對象,可以讀取其中的中繼資料。其中的GetType會返回一個用於表示指定程式集的type對象(讀取程式集中的所有類型用GetTypes會返回一個type對象的數組)。
       返回方法資訊(公用方法)
       MethodInfo mi = T.GetMethod("getList");
       根據前面type類型建立一個對象
       object o = Activator.CreateInstance(T);
       參數
       object[] par = new object[] { "E01" };
通過MethodInfo對象的Invoke方法,動態調用此方法,參數o是因為執行個體方法需要在調用時有一個執行個體存在.
       DataTable dt = (DataTable)mi.Invoke(o, par);
       調用返回的資料顯示列表中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.