Recently, someone called Insus to learn about Reflection. Reflection provides encapsulated assembly, module, and Type objects (Type ). You can use reflection to dynamically create instances of the type, bind the type to an existing object, or obtain the type from the existing object and call its method or access its fields and properties. If attributes are used in the code, you can use reflection to access them.
The following example shows how to set and get the attributes of a category in Insus.
First, write a class, and then write a read/write attribute:Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
/// <Summary>
/// Summary description for Member
/// </Summary>
Namespace Insus. NET
{
Public class Member
{
Private string _ Name;
Public string Name
{
Get
{
Return _ Name;
}
Set
{
_ Name = value;
}
}
Public Member ()
{
//
// TODO: Add constructor logic here
//
}
}
}
Insus. NET has always been writing the asp.net program, and the exercises are also conducted on the site.
Create a webpage and reference two namespaces:Copy codeThe Code is as follows: using Insus. NET;
Using System. Reflection;
Read/write attributes:Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using Insus. NET;
Using System. Reflection;
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
// Instantiate the class
Member objMember = new Member ();
// Set the attribute value
PropertyInfo pi = objMember. GetType (). GetProperty ("Name", BindingFlags. Public | BindingFlags. Instance );
If (null! = Pi & pi. CanWrite)
{
Pi. SetValue (objMember, "Insus. NET", null );
}
// Get value of the attribute
PropertyInfo pii = objMember. GetType (). GetProperty ("Name", BindingFlags. Public | BindingFlags. Instance );
If (null! = Pii & pi. CanRead)
{
Object obj_Name = pii. GetValue (objMember, null );
Response. Write (obj_Name.ToString ());
}
}
}