On the Relationship Between. Net reflection, delegated Technology and Design Mode

Source: Internet
Author: User
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... Net executable ApplicationProgramStructure

ProgramCodeAfter compilation, we first need to understand the structure of the 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.

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.

1 namespace reflectionexample
2 {
3 class class1
4 {
5 [stathread]
6 static void main (string [] ARGs)
7 {
8 system. Console. writeline ("list all types in the assembly ");
9 Assembly A = assembly. loadfrom (“reflectionexample.exe ");
10 type [] mytypes = A. gettypes ();
11
12 foreach (type T in mytypes)
13 {
14 system. Console. writeline (T. Name );
15}
16 system. Console. 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 ("instantiate helloworld and call sayhello 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 | bindingflags. 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 sayhello ()
21 {
22 if (myname = NULL)
23 {
24 system. Console. writeline ("Hello World ");
25}
26 else
27 {
28 system. Console. writeline ("hello," + myname );
29}
30}
31}
32}
33

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.
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.

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. 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}

The relationship between delegated technology and delegated 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.

Delegated technology and design mode 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.

Author blog: http://fineboy.cnblogs.com

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.