.NET reflection, commission technology and design patterns
1 reflection technology and design model
Reflection is an important mechanism in .NET, through radiation, members, including classes, structures, delegates, interfaces, and enumerations, etc., including methods, properties, events, and And constructor, etc. You can also get the name, qualifier, and parameters of each member. With reflections, you can make each type as a means. If you get the information of the constructor, you can create objects directly, even if the type of this object is not known when compiling.
1.1 .NET executable application structure
The program code generates executable applications after compiling, first we must understand the structure of this executable application.
The application structure is divided into application domain-assembly-module-type-member several levels, public language runtime loader management application domain, including loading each assembly to the corresponding application domain and control The memory layout of the type hierarchy of each program.
The assembly contains modules, and module contains types, and the types include members, and reflects provide encapsulating assemblies, modules, and type objects. We can create types of instances that are dynamically created, bind the type to an existing object or get the type from the existing object, and then call the type method or access its fields and properties. Reflection usually has the following use.
(1) Use assembly to define and load an assembly, and load the module in the assembly list, and the acquisition of the type and create the instance of this type.
(2) Using the Module Understand the assembly containing the module and classes in the module, you can also get all global methods or other specific non-global methods defined on the module.
(3) Using the ConstructorInfo to understand the name, parameters, access modifiers (such as PULIC or PRIVATE), and implementation details such as Abstract or Virtual. Use the Type's getConstructors or getConstructor method to call a specific constructor.
(4) Using the MethodInfo to understand the name, return type, parameter, access modifier (such as pullic or private) and implement details (such as Abstract or Virtual). Use the Type's getMethods or getMethod method to call a specific method.
(5) Use the FIEDINFO to understand the name of the field, access the modifier (such as public or private) and implement details (such as static), etc., and get or set a field value.
(6) Using EventInfo to understand the name of the event, the event handler data type, custom property, declaration type, and reflection type, etc., add or remove event handler.
(7) Using the PropertyInfo to understand the name, data type, declaration type, reflection type, and read or canable status, etc. of the property, to obtain or set the attribute value.
(8) Use ParameterInfo to understand the name of the parameter, data type, is the input parameter or output parameters, and the position of the parameters in the method signature.
System.Reflection.emit Namespace class provides a special reflection that can be constructed at runtime.
Reflection can also be used to create an application called type browser that enables users to select type and then view information about selected types.
In addition, language compilers such as JScript use reflection to construct symbol tables. System.Runtime.Serialization Namespace Class uses reflection to access the data and determine the field to be permanently saved, the class in the system.runtime.Remoting namespace is indirectly used by serialization. 1.2 Reflection Technology Example
Below is an example of reflection techniques, we can dynamically instantiate objects, obtain the properties of objects, and call the object.
1
Namespace Reflectionexample
2
{3 Class Class1 4 {5 [Stathread] 6 static void main (string [] args) 7 {8 system.console.writeline ("All Types in List Settings"); 9 Assembly A = assmbly.loadFrom (" ReflectionExample.exe "); 10 TYPE [] mytypes = a.gettypes (); 11 12 Foreach (Type Tin Mytypes) 13 {14 System.Console.writeline (T.Name); 15} 16 System.ConLe.Readline 17 System.console.writeline ("List all methods in Hellword"); 18 Type HT = TypeOf (HelloWorld); 19 methodInfo [] mif = ht.getMethods (); 20 Foreach (MethodInfo Mf in MIF) 21 {22 System.console.writeline (mf.name); 23} 24 System.Console.readLine (); 25 System.Console.writeline ("Instantiation HelloWorld, and calls Sayello Method"); 26 Object Obj = Activator.createInstance (HT); 27 string [] s = {"zhenlei"}; 28 Object bojname = activator.createInstance (HT, S); 29 bindingflags flags = (bindingflags.nonpublic | bindingflags.public | bindingf lags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); 30 MethodInfo msayhello = ht.GetMethod ( "SayHello"); 31 msayhello.Invoke (obj, null); 32 msayhello.Invoke (objName, null); 33 System.Console .Readline (); 34} 35} 36}
1
Using
System;
2
Namespace
Reflectionexample
3
{4 public class helloworld 5 {6 string myname = null; 7 public helloworld (string name) 8 {9 myname = name; 10} 11 public helloworld (): this (null) 12 {} 13 public string name 14 {15 get 16 {17 return myname; 18} 19} 20 public void syhello () 21 {22 if (MyName == null) 23 {24 System.Console.writ Eline ("Hello World"); 25} 26 else 27 {28 System . Console.writ Eline ("Hello," MyName; 29} 30} 31} 32} 33
1.3 Use reflection technology in design mode implementation
Reflective technology can simplify the implementation of the factory.
(1)
Factory method: By reflection, the subclass name that needs to be implemented can be passed to the factory method, so that there is no need to implement the instantiation of the class in the subclass.
(2)
Abstract factory: Use reflection to reduce the subclass of abstract factories.
Reflective technology can simplify the complexity of factory code, in the .NET project, the factory used reflection technology has basically replaced the factory method.
Reflective techniques can greatly simplify the generation of objects, and there is a great impact on the implementation of the following design patterns.
(1) Command mode: You can use the type name of the command as an instance of the command directly to the parameter, and the command can be dynamically executed.
(2) Enjoyment mode: Implementation of reflection technology can simplify the enjoys plant.
2 Principal technology and design model
The commission technology is an important technology introduced by .NET, using the entrusted dynamic binding of object behavior, thereby improving the design flexibility.
2.1. In the principal technology
The .NET runtime support is called "delegate" reference type, which effects similar to the function pointer in C . Unlike functional pointers, the entrusted instance is independent of the class of its packaging method, mainly those methods are compatible with the delegation type. In addition, the function pointer can only reference the static function, and the delegate can reference the static and instance methods. The commission is mainly used for event handler and callback functions in .NET Framework.
All delegates are inherited from System.Delegate and have a call list, which is a list of links to the method that is executed when the entrust is called. The resulting commission can reference any method with a matching signature, not to have a returned type and a delegate definition return value of multiple methods in the call list.
The entrusted Cimbine and REMOVE method can be used to add and remove methods in their call list. To call the delegate, use the Invoke method, or use the BeginInvoke and EndInvoke method asynchronous transfer committee. The implementation of the delegate is provided by the runtime, not by the user code.
Principal Applicable to the case where the function pointer needs to be used in some languages, but is different from the function pointer, it is object-oriented and type.
The entrustment defines a class, which is a class derived from the System.Delegate class. The entrustment instance encapsulates a call list, which lists one or more methods, and each method is called a callable body. For example, the modifier can be called by an instance and the method of the instance; for a static method, the calling entity is constructed only by one method. If a commission instance is called with a set of suitable parameters, each callable entity packaged in the delegate instance is called, and the same set of parameters described above is used. A useful attribute of the entrustment instance is that it does not know, and it is not careful about the details of its package method. The most important thing for it is that these methods are compatible with the type of commission. That is, as long as the return type and parameter table of the method is the same, the method is compatible with the delegate type, and the name of the method is not necessarily the same as the committee class.
Define and use the commission divided into declaration, instantiation, and call three steps. Entrusted to declare grammar statements, such as:
Delegate void mydelegate ();
Declare a delegate named MyDelegate, it does not have parameters and does not return any results, such as:
Class test
{
Static void f ()
{
System.console.writeline ("test.f");
}
Static void main ()
{
MyEdelegate D = New MyDelegate (f);
d ();
}
}
Create a MyDelegate instance and call it immediately. Don't make much sense, because the method directly calls the method is simpler. When it comes to its anonymous features, the entrusted can truly show its effect, such as:
Void Multicall (MyDelegate D, INT Count) {
For (int i = 0; i d (); } } A multicall method that repeats myDelegate is displayed. This method does not know, it is not known to know the type of MyDelegate's target method, which is accessibility or whether it is static. The most important thing for it is that the goal method is compatible with MyDelegate. 2.2 Example The following example illustrates the implementation of the commission, the code is as follows: 1 Using System; 2 Namespace Delegateexample 3 {4 Public Class TemplateMethod 5 {6 Public Delegate Float Comp (Float A, Float B); 7 Public Comp Mycomp; 8 Public TemplateMethod () 9 {} 10 Public Float Doc (Float [] f) 11 {12 float nf = float .Nan; 13 foreach (Float DF IN f) 14 {15 IF (Float.isnan (NF)) 16 & nbsp; NF = DF; 17 else18 & nbsp; nf = mycomp (nf, df); 19} 20 return nf ; 21} 2223} 24} 2.3 Relationship between commissioning technology and GOF design mode It should be noted that the principal technology in .NET consistent with the entrusted intent of GOF in the design mode, but there is a considerable difference in implementation. The entrustment in .NET further reduces the coupling between the objects, which will change the static combined relationship into a dynamic combination relationship at runtime. GOF defined in "Design Mode" is: "Entrusted is a combination method, which makes the combination have the same reuse capability with inheritance. In the entrustment mode, there are two objects to process a request, accept the request. Delegate the operation to its agent (delegate), which is similar to the subclass to hand over the parent class processing. When inheriting, the inherited operation is always referenced to the subject of accepting the request. In C through this member variable In SmallTalk, pass the Self. Principal to obtain the same effect, the acceptable object will pass itself to the client (agent), so that the authorized operation can reference the subject. " The above structure can be more flexible if it is adopted .NET. Window does not quote Rectangle to implement Area's calculations, first declare a delegation definition of a computing area, and sample code is as follows: Public delegate float darea (); However, in the Window class, declare the interface consistent with this agent: Class Window { Public Darea Area; } Here you don't need to reference the Rectangle class, just dynamically binding when executed: Rectangle rc = new rectangle (); Window w = new window (); W.area = New Darea (rc.area); This is actually called the Reactangel's AREA method when the W's area is called. From the implementation of the intent, .NET's commission can better achieve the intentments set flex in GOF, and more flexible structures. But these two entrustments solved are not a level of problems, and the entrustment of GOF emphasizes a strategy, while .NET and commissioning techniques are implemented. 2.4 Principal Technology and Design Mode Realization It is possible to further implement the idea of combining inheritance, many relationships with inheritance implementation can be implemented. The entrustment can simplify the use of the following design patterns. (1) Template method: This method adopts inheritance to achieve specific methods, and uses a commission that can dynamically implement a combination of methods. (2) Observer: You can use an event to entrust communication between the observer and the subject. (3) Intermediaries: Use the commission to remove the coupling relationship between the workpiece and the intermediaries.