First, reflection is the ability to dynamically discover type information. It helps program designers use some information to dynamically consume types while the program is running, which is unknown at design time, and is later bound by a type of capability. Reflection also supports more advanced behaviors that can dynamically create new types at run time, and invoke these new types of operations.
Ii. Some classes that are used frequently in reflection
Assembly class
The Assembly class is a reusable, version-free, self-describing common language runtime application building block. You can use the Assembly.Load and Assembly.LoadFrom methods to dynamically load assemblies.
Type class
The center of reflection is the System.Type class. The System.Type class is an abstract class that represents a type in a common type system. This class enables you to query the type name, the module and namespace contained in the type, and whether the type is a numeric type or a reference type.
The System.Type class enables you to query almost any type-related property, including type access qualifiers, types, COM properties of types, and so on.
Activator class
The Activator class supports dynamic creation of. NET Assemblies and COM objects. COM objects or assemblies can be loaded through Createcominstancefrom, CreateInstance, CreateInstanceFrom, GetObject, four static methods, and instances of the specified type are created.
Binder Class
The Binder class is a binder used to perform type conversions, and the InvokeMember method of the Type object accepts binders objects that describe how to convert the arguments passed to invokemember into the type that the method actually requires.
The Binder class is an abstract class that requires overriding methods BindToMethod, Bindtofield, Selectmehtod, Selectproperty, and changetype to create binders.
DefaultMemberAttribute class
The DefaultMemberAttribute class is used for types with a string parameter that indicates the default member name. The ability to invoke the default member through InvokeMember without the need to pass the name of the calling member. It can be used when a binder is required but no special binding behavior is required.
There are also classes describing element type information, Construtorinfo (constructors), MethodInfo (methods), FieldInfo (Fields), PropertyInfo (attributes), EventInfo (events), MemberInfo (member), ParameterInfo (parameter). If the query obtains an instance of any type of information, you can obtain the type information of any element in the type, and for security reasons, there is no guarantee that any information in the Assembly will be obtained.
Iv. examples
Class definition
Code
Using System;
Using System.Collections.Generic;
Using System.Text;
Namespace Reflectionsample
{
/**//**//**////
Description: A simple class
Wen Ye
Contact: stwyhm.cnblog.com
///
public class Classsample
{
Default constructs
Public Classsample ()
{
THIS.name = "You have called the default construct to create a class instance. ";
}
With parametric construction
Public classsample (string name)
{
THIS.name = name;
}
Field
public string name;
public string Field;
Property
private string property;
public string Property
{
set {This.property = value;}
get {return property;}
}
Public method
public string Publicclassmethod ()
{
return string. Format ("You have reflected a public method");
}
Private method
private String Privateclassmethod ()
{
return string. Format ("You reflect a private method");
}
static method
public static string Staticmethod ()
{
Return "You have reflected a static method";
}
Method of participation
public string Parametermethod (string para)
{
return para;
}
public event EventHandler EventHandler;
public void Doevent ()
{
EventHandler (Null,eventargs.empty);
}
}
}
Reflection Example
Code
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;
Using Reflectionsample;
/**//**//**////
Description: A simple example of using reflection
Wen Ye
Contact: stwyhm.cnblog.com
///
public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{
String path = Server.MapPath (Request.path);
String FilePath = path. Substring (0, path. LastIndexOf (' \ \ ')) + @ "\bin\reflectionsample.dll";
Get assembly
Assembly classsampleassembly = Assembly.LoadFrom (FilePath);
Getting the specified object type from an assembly
Type Classsampletype = Classsampleassembly.gettype ("Reflectionsample.classsample");
Create an instance using activator create an instance using Activator #region Create an instance using Activator
Creating an object instance from an object type
Classsample S1 = activator.createinstance (classsampletype) as classsample;
Response.Write (S1.name + "(using activator to create an instance)");
#endregion
Dynamic call constructor Dynamic call constructor #region dynamic call constructor
Call no parameter constructs
ConstructorInfo StudentConstructor1 = Classsampletype.getconstructor (new type[] {});
Classsample s2 = studentconstructor1.invoke (new object[] {}) as classsample;
Response.Write (S2.name + "");
Call a parameter construct
ConstructorInfo StudentConstructor2 = Classsampletype.getconstructor (new type[] {typeof (String)});
Classsample s3 = Studentconstructor2.invoke (new object[] {"You have called a parameter construct to create a class instance. "}) as Classsample;
Response.Write (S3.name + "");
#endregion
Reflection Method #region Reflection method
Calling a non-static method
String returnValue1 = Classsampletype.invokemember ("Publicclassmethod", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, NULL, S1, new object[] {}) As String;
Response.Write (returnValue1 + "");
Calling a static method
String returnValue2 = Classsampletype.invokemember ("Staticmethod", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, NULL, S1, new object[] {}) As String;
Response.Write (ReturnValue2 + "");
Calling Private methods
String returnValue3 = Classsampletype.invokemember ("Privateclassmethod", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, NULL, S1, new object[] {}) As String;
Response.Write (ReturnValue3 + "");
#endregion
Reflection parameter Reflection parameter #region reflection parameter
MethodInfo Parametermethod = Classsampletype.getmethod ("Parametermethod");
Parameterinfo[] paras = parametermethod.getparameters ();
for (int i = 0; I ", new object[] {paras[i]. Name, Paras[i]. Parametertype.tostring (), Paras[i]. Isoptional.tostring (), Paras[i]. Position.tostring (), Paras[i]. Defaultvalue.tostring ()}));
#endregion
Reflection Property Reflection Property #region Reflection Property
Classsampletype.invokemember ("Property", BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance, NULL, S1, new object[] {"You have reflected an attribute"});
String returnValue4 = Classsampletype.invokemember ("property", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, NULL, S1, new object[] {}) As String;
Response.Write (ReturnValue4 + "");
#endregion
Reflection Field Reflection Field #region Reflection field
Classsampletype.invokemember ("Field", Bindingflags.setfield | BindingFlags.Public | BindingFlags.Instance, NULL, S1, new object[] {"You reflect a field"});
String returnValue5 = Classsampletype.invokemember ("Field", Bindingflags.getfield | BindingFlags.Public | BindingFlags.Instance, NULL, S1, new object[] {}) As String;
Response.Write (ReturnValue5 + "");
#endregion
}
}
V.. NET reflection mechanism
The. NET reflection mechanism provides an alternative to creating objects and invoking other methods. For example, to improve the flexibility of the code. But the problem is that we have to write more code to do it. There are some drawbacks to using the reflection mechanism. The biggest drawback is that the compiler is unable to type check the object, and the IDE's IntelliSense will be powerless. But where is his real advantage? It provides a means to defer specifying a specific class to a running time. Four steps to invoke a method using the reflection mechanism: 1 Loading assemblies 2 getting the type of a class 3 Creating an instance of this class 4 methods to invoke this instance There are two static methods Assembly.Load (String assemblyname) and Assembly.LoadFrom (string fileName) in the System.Reflection.Assembly class To load the assembly into the application-order domain. PS: In. NET what happens behind the scenes when an object is created? When we run an application, the. NET CLR first creates an application domain to hold the application, and then loads the assembly that should be referenced into the application domain. Where MSCorLib.dll is an assembly that contains many of the classes in the System namespace and its sub-namespaces: System; System.text,system.io and so on. The program in the collection. The CLR then loads the assembly to which the running application belongs. DEMO:
(1) Namespace Classlibrarysport { Public abstract class Sport { protected string name; Public abstract string GetName (); Public abstract string getduration (); } } = = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = = (2) namespace Classlibrarysomesports//The project added a reference to (1) { public class Football:ClassLibrarySport.Sport { Public Football () { Name = "Football"; } public override string GetName () { return name; } public override string Getduration () { Return "four minute quarters"; } } } = = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = = (3) namespace Consoleassemblytest//The project added a reference to (1) { Class Program { static void Main (string[] args) { Assembly Assembly = Assembly.LoadFrom (@ "E:\ClassLibrarySomeSports\ Bin\debug\classlibrarysomesports.dll "); Type[] Types = assembly. GetTypes (); Console.WriteLine ("Get Type from ClassLibrarySomeSports.dll:"); for (int i = 0; i < types. Length; i++) { Console.WriteLine (Types[i]. Name); } Use the GetConstructor () method to get the constructor of the corresponding type to construct an object of that type Console.WriteLine ("Use Method getconstructor ():"); ConstructorInfo ci = types[0]. GetConstructor (new type[0]); Classlibrarysport.sport Sport = (classlibrarysport.sport) ci. Invoke (new object[0]); Console.WriteLine (Sport. GetName () + "has" + sport. Getduration ()); Use the Activator.CreateInstance () method to construct an object of that type Use assembly. CreateInstance () returns to NULL,?? Console.WriteLine ("Use Method CreateInstance ():"); Classlibrarysport.sport Sport1 = (classlibrarysport.sport) Activator.CreateInstance (Types[0]); Console.WriteLine (Sport1. GetName () + "has" + sport1. Getduration ()); Reflects a method with the name "Getduration" in the specified type, and executes the method through the Invoke () method Object objsport = Activator.CreateInstance (Types[0]); MethodInfo method = Types[0]. GetMethod ("Getduration"); Object o = method. Invoke (Objsport, New object[0]); Console.WriteLine (o as String); Console.read (); } } } = = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = = Output: Get Type from ClassLibrarySomeSports.dll: Football Use Method getconstructor (): Football have four minute quarters Use Method CreateInstance (): Football have four minute quarters Four minute quarters |
. NET Reflection