Dynamically calling methods in a specified assembly using. net reflection

Source: Internet
Author: User
Each. net Assembly contains metadata in addition to code. Metadata includes information about the Assembly, such as the version number, the referenced assembly, and all types of information, including its methods, attributes, and fields. Using. net reflection, you can read this information at runtime and call Methods dynamically.
The project is almost finished, and finally we have time to write a blog ,,
An example of dynamically calling the specified method of an assembly is provided.
Project 1 (Demo) contains a Test class. The Test class writes a getList method, and the data returned by this method is manually added. The source code is as follows:
Project 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"] = "Zhangling ";
Dr ["sex"] = "male ";
Dt. Rows. Add (dr );
Dr = dt. NewRow ();
Dr ["id"] = "zl ";
Dr ["name"] = "Li Si ";
Dr ["sex"] = "female ";
Dt. Rows. Add (dr );
Return dt;
}
}
}

Project 2 (DemoXml) contains a Test class. The Test class writes a getList method, and the data returned by this method is read from the database. The source code is as follows:
Project 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. deleettings ["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 ("exception:" + ex. Message + ex. StackTrace );
}
Finally
{
Cn. Close ();
Cn = null;
}
}
}
}

Project 3 (WebDemo) demonstrates dynamically returning a DataTable using the getList method in the specified dataset, and displaying the returned data with a gridview.
Call demo
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 ();
}
}
Data initialization, which can be configured in the web. config file # region data initialization, which can be configured in the web. config file
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"] = "loading Custom Data ";
Dr ["filepath"] = Server. MapPath (@ "Files \ Demo. dll ");
Dt. Rows. Add (dr );
Dr = dt. NewRow ();
Dr ["name"] = "loading xml data ";
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 dropdownlistincluselectedindexchanged (object sender, EventArgs e)
{
Try
{
// Read the specified dll file
String strPath = (sender as DropDownList). SelectedValue. Trim ();
String NameSpace = this. DropDownList1.SelectedIndex = 0? "Demo. Test": "DemoXml. Test ";
// Load the memory of the specified assembly
Assembly assembly = Assembly. LoadFrom (strPath );
// If a specified object in the add-back Assembly returns all objects, GetTypes () is used to return the array of A Typt object.
Type T = assembly. GetType (NameSpace );
// Return method Information (Public method)
MethodInfo mi = T. GetMethod ("getList ");
// Create an object based on the previous type
Object o = Activator. CreateInstance (T );
// Parameters
Object [] par = new object [] {"E01 "};
// Call this method dynamically through the Invoke method of the MethodInfo object. The parameter o is because an instance exists when the instance method is called.
DataTable dt = (DataTable) mi. Invoke (o, par );
This. GridView1.DataSource = dt;
This. GridView1.DataBind ();
}
Catch (Exception ex)
{
// Do Exception
}
}
}

The Assembly object returned by the Assembly. LoadFrom method can read the metadata. GetType returns a type object used to indicate the specified assembly (reading all types in the assembly using GetTypes will return an array of type objects ).
Return method Information (Public method)
MethodInfo mi = T. GetMethod ("getList ");
Create an object based on the previous type
Object o = Activator. CreateInstance (T );
Parameters
Object [] par = new object [] {"E01 "};
Call this method dynamically using the Invoke method of the MethodInfo object. The parameter o is because an instance exists when the instance method is called.
DataTable dt = (DataTable) mi. Invoke (o, par );
The data returned by the call is displayed in the list.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.