. NET reflection, delegated Technology and Design Model

Source: Internet
Author: User
Tags emit
. NET reflection, delegated Technology and Design Model

1. Reflection Technology and Design Model 
Reflection (Reflection) is. NET, which can be obtained at runtime through radiation. NET, including methods, attributes, events, and constructor. You can also obtain the name, qualifier, and parameters of each member. With reflection, you can be familiar with every type. If you obtain information about the constructor, you can directly create an object, even if the object type is unknown during compilation.

 

1.1. NET executable application structure
The program code is compiled to generate an executable application. First, we need to understand the structure of this executable application.
The application structure can be divided into application domain-assembly-module-type-member layers, and the common language runtime loader manages the application domain, such management includes loading each assembly to the corresponding application domain and controlling the memory layout of the type hierarchy of each set.
The Assembly contains modules, while the module contains types and types, and reflection provides encapsulated assembly, module, and type objects. We 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 then call the method of the type or access its fields and attributes. Reflection is usually used for the following purposes.
(1) Use Assembly to define and load the Assembly, load the module in the Assembly list, and locate the type in this Assembly and create instances of this type.
(2) Use the Module to understand the Assembly containing the Module and the classes in the Module, and obtain all global methods or other specific non-Global methods defined on the Module.
(3) Use ConstructorInfo to understand the name, parameters, access modifiers (such as pulic or private) and implementation details (such as abstract or virtual) of the ConstructorInfo. Use the GetConstructors or GetConstructor method of Type to call a specific constructor.
(4) use MethodInfo to understand the method name, return type, parameters, access modifiers (such as pulic or private), and implementation details (such as abstract or virtual. Use the GetMethods or GetMethod method of Type to call a specific method.
(5) Use FiedInfo to learn the field name, access modifier (such as public or private), implementation details (such as static), and obtain or set the field value.
(6) Use EventInfo to learn about the event name, event handler data type, custom attributes, declaration type, and reflection type, and add or remove event handlers.
(7) Use PropertyInfo to understand the attribute name, data type, declaration type, reflection type, read-only or writable status, and obtain or set the attribute value.
(8) Use ParameterInfo to know the parameter name, data type, input parameter, output parameter, and the parameter location in the method signature.
The System. Reflection. Emit namespace class provides a special form of Reflection that can be constructed at runtime.
Reflection can also be used to create an application called a type browser, allowing you to select a type and view information about the selected type.
In addition, Jscript and other language compilers use reflection to construct symbol tables. Classes in the System. Runtime. Serialization namespace use reflection to access data and determine the fields to be permanently saved. classes in the System. Runtime. Remoting namespace use reflection indirectly through Serialization.

1.2 reflection technical example
The following is an example of reflection technology. We can dynamically instantiate an object when the program gets it, obtain the object attributes, and call the object method.

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Reflection;
Using System. Reflection. Emit;

Namespace ReflectionExample
{
Class Class1
{
[STAThread]
Static void Main (string [] args)
{
System. Console. WriteLine ("list all types in the assembly ");
Assembly a = Assembly. LoadFrom ("leleapplication1.exe ");
Type [] mytypes = a. GetTypes ();
 
Foreach (Type t in mytypes)
{
System. Console. WriteLine (t. Name );
}
System. Console. ReadLine ();
System. Console. WriteLine ("list all methods in HellWord ");
Type ht = typeof (HelloWorld );
MethodInfo [] mif = ht. GetMethods ();
Foreach (MethodInfo mf in mif)
{
System. Console. WriteLine (mf. Name );
}
System. Console. ReadLine ();
System. Console. WriteLine ("instantiate HelloWorld and call SayHello method ");
Object obj = Activator. CreateInstance (ht );
String [] s = {"zhenlei "};
Object objName = Activator. CreateInstance (ht, s );
BindingFlags flags = (BindingFlags. NonPublic | BindingFlags. Public | BindingFlags. Static | BindingFlags. Instance | BindingFlags. DeclaredOnly );
MethodInfo msayhello = ht. GetMethod ("SayHello ");
Msayhello. Invoke (obj, null );
Msayhello. Invoke (objName, null );
System. Console. ReadLine ();
}
}
}

Namespace ReflectionExample
{
Public class HelloWorld
{
String myName = null;
Public HelloWorld (string name)
{
MyName = name;
}
Public HelloWorld (): this (null)
{}
Public string Name
{
Get
{
Return myName;
}
}
Public void SayHello ()
{
If (myName = null)
{
System. Console. WriteLine ("Hello World ");
}
Else
{
System. Console. WriteLine ("Hello," + myName );
}
}
}
}

1.3 Use reflection technology in design mode implementation
Reflection technology can simplify factory implementation.
(1) Factory method: The subclass name to be implemented can be passed to the factory method through reflection, so that class instantiation is not required in the subclass.
(2) Abstract Factory: Using Reflection can reduce subclass of abstract factory.
Using Reflection technology can simplify the complexity of Factory Code. In the. NET project, factories using reflection technology have basically replaced the factory method.
The reflection technology can greatly simplify the generation of objects and greatly affect the implementation of the following design patterns.
(1) command mode: You can use the command type name as a parameter to directly obtain the command instance and dynamically execute the command.
(2) metadata sharing mode: Using Reflection technology to instantiate the metadata sharing mode can simplify the metadata sharing factory.

 

2 delegated Technology and Design Model
Delegation is an important technology introduced by. NET. With delegation, object behavior can be dynamically bound to improve design flexibility.

2.1 delegate Technology in. NET
The. NET Runtime Library supports a reference type called "delegate", which is similar to the function pointer in C ++. Unlike function pointers, the delegated instance is independent of its encapsulated method class, mainly because those methods are compatible with the delegate type. In addition, the function pointer can only reference static functions, and the delegate can reference static and instance methods. Delegation is mainly used for event handlers and callback functions in. NET Framework.
All delegates are inherited from System. Delegate and have a call list. This is a link list of the methods executed when the Delegate is called. The generated delegate can reference any method with a matched signature. It does not define the return value for the delegate that has a return type and contains multiple methods in the call list.
You can use the delegate Cimbine and Remove methods to add and Remove methods in the call list. To call a delegate, you can use the Invoke method or the BeginInvoke and EndInvoke methods to call the delegate asynchronously. The implementation of the delegate class is provided by the runtime rather than the user code.
Delegation is applicable to situations where function pointers are needed in some languages, but unlike function pointers, It Is Object-Oriented and type-safe.
The Delegate Declaration defines a class that is derived from the System. Delegate class. The delegated instance encapsulates a call list, listing one or more methods. Each method is called a callable object. For an instance method, the callable object consists of an instance and the method of the instance. For a static method, the callable object consists of only one method. If a set of suitable parameters are used to call a delegate instance, each callable entity encapsulated by the delegate instance is called and the same set of parameters are used.
A useful attribute of a delegated instance is that it does not know or care about the details of the class to which its encapsulation method belongs. The most important thing for it is that these methods are compatible with the delegate type. That is, as long as the return type and parameter table of the method are the same, the method is compatible with the delegate type, and the method name does not have to be the same as the delegate class.
The definition and use of delegation are divided into three steps: Declaration, instantiation, and call. Statement of delegate statement syntax, such:
Delegate void myDelegate ();
Declare a delegate named myDelegate without parameters and no results are returned, for example:
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. This does not make much sense, because directly calling a method is easier. Only when the anonymous feature is involved can the delegate truly display its effect, such:
Void MultiCall (myDelegate d, int count ){
For (int I = 0; I <count; I ++ ){
D ();
}
}
Display a MultiCall method that repeatedly calls myDelegate. You do not need to know the type of the target method of myDelegate, the accessibility of the method, or whether the method is static. Most importantly, the target method is compatible with myDelegate.

2.2 example
The following example illustrates the implementation of delegation. 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 DoComp (float [] f)
11 {
12 float nf = float. NaN;
13 foreach (float df in f)
14 {
15 if (float. IsNaN (nf ))
16 nf = df;
17 else
18 nf = myComp (nf, df );
19}
20 return nf;
21}
22
23}
24}

2.3 relationship between entrusting technology and entrusting in the gof Design Model
It should be noted that the delegate Technology in. NET is consistent with the intent of the delegate mentioned in GOF's design pattern, but there are quite a big difference in implementation methods .. The delegation in NET further reduces the coupling between objects and changes static composite relationships to dynamic composite relationships at runtime.
In design patterns, GOF defines the principal as: "A principal is a combination method that allows a combination to have the same reuse capability as inheritance. In the delegate mode, two objects are involved in processing a request. The object that receives the request delegates the operation to its proxy (delegate), which is similar to the parent class that the subclass sends the request. When inheritance is used, the inherited operation can always reference the object that receives the request. Use this member variable in C ++ and self in Smalltalk. In order to achieve the same effect, the object that receives the request will pass itself to the entrusted person (agent), so that the entrusted operation can reference the object that accepts the request ."
If the. NET delegated technology is used, the above structure can be more flexible. Window does not reference Rectangle to implement Area calculation. Therefore, a delegated definition of the calculated Area is first declared. The sample code is as follows:
Public delegate float Darea ();
However, the Window class declares the same interface as this proxy:
Class Window
{
Public Darea Area;
}
The Rectangle class does not need to be referenced here, but it can be dynamically bound during execution:
Rectangle rc = new Rectangle ();
Window w = new Window ();
W. Area = new Darea (rc. Area );
In this way, the Reactangel Area method is actually called when the Area of w is called. From the perspective of implementation intent, the. NET delegate can better implement the intent stated by GOF, and the structure is more flexible. However, these two kinds of delegation solve not one level of problems. The GOF delegation emphasizes a strategy, while the. NET and delegation technologies are specific implementations.

 

2.4 delegated technology and design model implementation
The delegated technology can be used to further implement the idea of replacing inheritance with combinations. Many inheritance-implemented relationships can be implemented using delegation. Delegation can simplify the use of the following design patterns.
(1) template method: This method uses inheritance to implement a specific method, and a combination of delegate methods that can be dynamically implemented.
(2) Observer: event Delegate can be used to implement communication between observer and topic.
(3) intermediary: Using delegation can remove the coupling relationship between the workpiece and the intermediary.

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.