Detailed explanation of C # reflection mechanism

Source: Internet
Author: User
Tags class definition
Definition of Reflection: the ability to review metadata and collect type information about it, metadata (the edited basic data unit) is a large list of tables, the compiler creates a class definition table, a field definition table, a method definition table, and so on, The System.Reflection namespace contains several classes that allow you to reflect (parse) the code of these meta data


I. The role of Reflection:
Dynamically create an instance of a type, set the type state to an existing object, or get a type from an existing object
The application needs to load a specific type from a particular assembly at run time so that a task can be implemented with reflection
Reflection is primarily applied to class libraries, which need to know the definition of a type to provide more functionality


Second, the application points:
Reflection is rarely used in real-world applications
Using reflection dynamic bonding requires sacrificing performance
Some meta data information is not available through reflection
Some reflection types are specifically developed for use by those CLR development editors, so you want to mean that not all reflection types are available


Third, the method of obtaining assembly:
Assembly.Load
Assembly.loadfile
Assembly.LoadFrom
assembly method of type Object


Iv. reflected members:
Memberinfo-Members
Constructorinfo-structure
fieldinfo-Field
Methodinfo-method
Propertyinfo-Property
eventinfo-Events


To obtain the member information of an object based on reflection
private void Writereflectioninfo ()
{
Type Testtype = typeof (Test);
Assembly Assembly = testtype.assembly;
Response.Write ("Assembly:" + Assembly.) FullName + "<br/>");
Type[] typelist = assembly.   GetTypes (); Get type
Get detailed information for each type
foreach (type type in typelist)
{
Response.Write ("------------------------" + type. Namespace + type. Name + "------------------------<br/>");
Getting the structure information of a type
Constructorinfo[] Constructs = type. GetConstructors ();


Get field information for a type
fieldinfo[] fields = type. GetFields ();
Response.Write ("<b> Class of public field information as follows:</b>" + "<br/>");
int a1 = 1;
foreach (FieldInfo field in fields)
{
Response.Write ((a1++). ToString () + "." + field. Name + "<br/>");
}


Get method information
Methodinfo[] methods = type. GetMethods ();


Response.Write ("<b> public methods are as follows:</b>" + "<br/>");
int a2 = 1;
foreach (MethodInfo method in methods)
{
parameterinfo[] Parameters = method. GetParameters ();
ParameterInfo Reparam = method. Returnparameter;
Response.Write ((a2++). ToString () + "." + Reparam. Parametertype.name + "" + method. Name + "(");
int index = 0;
foreach (ParameterInfo para in parameters)
{
if (index++ < parameters. LENGTH-1)
Response.Write (para. Parametertype.name + "" + para. Name + ",");
Else
Response.Write (para. Parametertype.name + "" + para. Name);
}
Response.Write (") <br/>");
}


Get information about a property
propertyinfo[] Propertys = type. GetProperties ();


Response.Write ("<b> Class of public properties as follows:</b>" + "<br/>");
int a3 = 1;
foreach (PropertyInfo Pro in Propertys)
{
Response.Write ((a3++). ToString () + "." + Pro. Propertytype.name + "" + Pro. Name + "{");
if (pro. CanRead) Response.Write ("get;");
if (pro. CanWrite) Response.Write ("set;");
Response.Write ("}<br/>");
}
Get event Information
Eventinfo[] Events = type. GetEvents ();


Response.Write ("<b> members of the following:</b>" + "<br/>");
Get members
int a4 = 1;
foreach (MemberInfo mi in type. GetMembers ())
{
Response.Write ((a4++). ToString () + "." + mi. Membertype.tostring () + ":" + mi. Name + "<br/>");
}
}


Vi. Dynamic creation of objects
The CreateInstance method of assembly object
Activator. CreateInstance method
InvokeMember method of type Object
Using the assembly CreateInstance method to obtain an instance of an object
private void Assembly_createinstance ()
{
String assemblyname = "Sqlmodel";
String className = AssemblyName + ". Member ";
To create an instance without parameters
Idal. Imember member = (idal. Imember) Assembly.Load (AssemblyName). CreateInstance (ClassName);
Response.Write ("Create no Parameter instance:" + member.id + "<br/>");
Create a parameter instance
object[] Parameters = new Object[1];
Parameters[0] = 10000;
Idal. Imember member1 = (idal. Imember) Assembly.Load (AssemblyName). CreateInstance (ClassName, False, Bindingflags.default, NULL, parameters, NULL, NULL);
Response.Write ("Create a Parameter instance:" + member1.id + "<br/>");
}


Using the Activator CreateInstance method to obtain an instance of an object
private void Activator_createinstance ()
{
String assemblyname = "Sqlmodel";
String className = AssemblyName + ". Member ";
To create an instance without parameters
System.Runtime.Remoting.ObjectHandle obj = Activator.CreateInstance (assemblyname, ClassName);
Idal. Imember member = (idal. Imember) obj. Unwrap ();
Response.Write ("Create no Parameter instance:" + member.id + "<br/>");
Create a parameter instance
object[] Parameters = new Object[1];
Parameters[0] = 10000;
System.Runtime.Remoting.ObjectHandle obj1 = Activator.CreateInstance (AssemblyName, ClassName, False, Bindingflags.createinstance, NULL, parameters, NULL, NULL, NULL);
Idal. Imember member1 = (idal. Imember) obj1. Unwrap ();
Response.Write ("Create a Parameter instance:" + member1.id + "<br/>");
}


Use the InvokeMember method of type to get an instance of an object
private void Type_invokemember ()
{
String assemblyname = "Sqlmodel";
String className = AssemblyName + ". Member ";
Assembly Assem = Assembly.Load (AssemblyName);
Type type = Assem.   GetType (ClassName); If you use Type.GetType to get type here, then assemblyname the specified class must be strong named
To create an instance without parameters
Idal. Imember member = (idal. Imember) type. InvokeMember (className, bindingflags.createinstance, NULL, NULL, NULL);
Response.Write ("Create no Parameter instance:" + member.id + "<br/>");
Create a parameter instance
object[] Parameters = new Object[1];
Parameters[0] = 10000;
Idal. Imember member1 = (idal. Imember) type. InvokeMember (className, bindingflags.createinstance, NULL, NULL, parameters);
Response.Write ("Create a Parameter instance:" + member1.id + "<br/>");
}


Vii. Dynamic Invocation Object method


InvokeMember method of type Object
Invoke method of MethodInfo object
The InvokeMember method of the type object to invoke the method dynamically
private void InvokeMember ()
{
String assemblyname = "Sqlmodel";
String className = AssemblyName + ". Member ";
String methodname = String.Empty;
string result = String.Empty;
Assembly Assem = Assembly.Load (AssemblyName);
Object obj = Assem. CreateInstance (ClassName);
Type type = Assem.   GetType (ClassName); If you use Type.GetType to get type here, then assemblyname the specified class must be strong named
Dynamic invocation of a method without parameters
methodname = "GetName";
result = (string) type. InvokeMember (methodname, BindingFlags.InvokeMethod, NULL, obj, NULL);
Response.Write (methodname + "method return value: + result +" <br/> ");
Dynamic invocation of methods with parameters
methodname = "Update";
object[] Methodparams = new Object[1];
Methodparams[0] = DateTime.Now;
result = (string) type. InvokeMember (methodname, BindingFlags.InvokeMethod, null, obj, methodparams);
Response.Write (methodname + "method return value: + result +" <br/> ");
A method with parameters for dynamic invocation of parametric schema functions
object[] Parameters = new Object[1];
Parameters[0] = 10000;
obj = Assem. CreateInstance (classname,false,bindingflags.createinstance, NULL, parameters, NULL, NULL);
result = (string) type. InvokeMember (methodname, BindingFlags.InvokeMethod, null, obj, methodparams);
Response.Write (methodname + "method return value: + result +" <br/> ");
}


Invoke method of MethodInfo object to invoke method dynamically


private void Methodinfo_invoke ()
{
String assemblyname = "Sqlmodel";
String className = AssemblyName + ". Member ";
String methodname = String.Empty;
string result = String.Empty;


Assembly Assem = Assembly.Load (AssemblyName);
Object obj = Assem. CreateInstance (ClassName);
Type type = Assem.   GetType (ClassName); If you use Type.GetType to get type here, then assemblyname the specified class must be strong named
Dynamic invocation of a method without parameters
methodname = "GetName";
MethodInfo MethodInfo = type. GetMethod (methodname);
result = (string) methodinfo.invoke (obj, null);
Response.Write (methodname + "method return value: + result +" <br/> ");
Dynamic invocation of methods with parameters
methodname = "Update";
object[] Methodparams = new Object[1];
Methodparams[0] = DateTime.Now;
MethodInfo method = Type. GetMethod (methodname);
result = (string) method. Invoke (obj, methodparams);
Response.Write (methodname + "method return value: + result +" <br/> ");
}


--------------------------------------------------------------------------------
The sqlmodel.member used above are:
Create a new Sqlmodel class library under which to create a member's class


Namespace Sqlmodel
{
public class Member:idal. Imember
{
private int _id = 100;
public int ID
{
get {return _id;}
set {_id = value;}
}
private string _name = "Limin";
public string Name
{
get {return _name;}
set {_name = value;}
}


Public member () {}
Public member (int ID)
{
_id = ID;
}


private void Init ()
{ }


public string GetName ()
{
return _name;
}
public string Update (DateTime cdate)
{
Return "{" + String.Format ("id:{0},name:{1},createdate:{2}", _id,_name,cdate) + "}";
}
}

}

Recommended Blog:

Http://www.cnblogs.com/yazdao/archive/2012/03/31/2426458.html

Http://www.cnblogs.com/yaozhenfa/p/CSharp_Reflection_1.html



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.