C # reflection and delegation methods in the method (small instance)

Source: Internet
Author: User

During the development process, static methods are called by adding a vertex after the type name and then the name of the called method. The method called for a type instance is called by a new object, add the method name, which is the most familiar method. You can also call it by reading CLR metadata and using reflection. When calling methods using Reflection, the two most important classes are System. Type and System. Reflection. MethodInfo. To call a method using the MethodInfo-type Invoke method, you must pass in the reference of the target object instance. As follows:

Public class Calculate
{
Private int Add (int leftNum, int rightNum)
{
Return leftNum + rightNum;
}
Protected string Hello (string name)
{
Return "Hello:" + name;
}
}

Delegation Method

Any object can call a delegate, as long as the method return value and method signature are the same as the delegate declaration.

  public delegate int DelegateCaculate(int a,int b);
public class Calculatetest
{
public int Add(int num1, int num2)
{
return num1+num2;
}
public static int Subtract(int num1,int num2)
{
return num2 - num1;
}
}

Console call:

Class Program
{
Static void Main (string [] args)
{
// Use the type. getmethod method to obtain the type method. BindingFlags sets the range of the search method.
// This column is a public method, private method, and non-static method. If you want to find a static method
// BindingFlags. Static needs to be set
System. Reflection. MethodInfo method = typeof (Calculate). GetMethod ("Add", BindingFlags. Public | BindingFlags. NonPublic | BindingFlags. Instance );
If (method = null)
Return;
// Call method parameters
Object [] paras = {10, 20 };
// Target object instance: new Calculate ()
Object result = method. Invoke (new Calculate (), paras );
Console. WriteLine (result );
System. Reflection. MethodInfo mt = typeof (Calculate). GetMethod ("Hello", BindingFlags. Public | BindingFlags. NonPublic | BindingFlags. Instance );
If (mt = null)
Return;
// Call method parameters
Object [] para = {"Li Guanghui "};
Object rs = mt. Invoke (new Calculate (), para );
Console. WriteLine (rs );
Console. ReadLine ();

// Delegate call
DelegateCaculate add = new DelegateCaculate (new Calculatetest (). Add );
DelegateCaculate subtract = new DelegateCaculate (Calculatetest. Subtract );
Console. WriteLine ("add:" + add (10, 20 ));
Console. WriteLine ("subtract:" + subtract (10, 20 ));
Console. ReadLine ();
}
}

Delegation and Interface

Interfaces and delegates have the ability to call specific methods, so they are very similar in this regard. However, the type declaration of the target method must be compatible with the interface, and the delegate can be called by any type, as long as the target method signature of the type matches the delegate signature.

So when to use the delegate and when to use the interface? msdn summarized it very well and I pasted it directly,

Delegation is useful in the following scenarios:

1. Call a single method.

2. A class requires multiple implementations of method specifications.

3. You want to allow static methods to be standardized.

4. Design Patterns for similar events.

5. The caller does not need to know or obtain the object of the method that matches the delegate signature.

6. The implemented provider only needs to implement the "distribution" Specification for a few selected components.

7. A combination of required methods.

Interfaces are useful in the following scenarios:

1. define a set of related methods.

2. Classes are generally only implemented once.

3. The caller of an interface wants to convert the interface type to another interface or class.

1 private void callObjectEvent (Object obj, string EventName)
2 {
3 // create a type. AssemblyQualifiedName has a valid name.
4 Type t = Type. GetType (obj. GetType (). AssemblyQualifiedName );
5 // parameter object
6 object [] p = new object [1];
7 // Generation Method
8 MethodInfo m = t. GetMethod (EventName, BindingFlags. NonPublic | BindingFlags. Instance );
9 // assign values to parameters. Input Function
10 // obtain parameter information
11 ParameterInfo [] para = m. GetParameters ();
12 // obtain the null value of the parameter based on the parameter name.
13 p [0] = Type. GetType (para [0]. ParameterType. BaseType. FullName). GetProperty ("Empty ");
14 // call
15 m. Invoke (obj, p );
16 return;
17}
18
19 // call example.
20 // call The onclick of Button1
21 callObjectEvent (Button1, "OnClick ");
22
23 // call the OnKeyPress of Button5
24 callObjectEvent (Button5, "OnKeyPress ");
25
26 // call OnTextChanged of Text1
27 callObjectEvent (Text1, "OnTextChanged ");
Private void callObjectEvent (Object obj, string EventName, EventArgs e = null)
{
// Create a type
// Type t = typeof (obj. GetType );
Type t = Type. GetType (obj. GetType (). AssemblyQualifiedName );
// Generation Method
MethodInfo m = t. GetMethod (EventName, BindingFlags. NonPublic | BindingFlags. Instance );
// Assign values to parameters. Input Function
// Obtain parameter information
ParameterInfo [] para = m. GetParameters ();
// Obtain the null value of the parameter based on the parameter name.
// Parameter object
Object [] p = new object [1];
If (e = null)
P [0] = Type. GetType (para [0]. ParameterType. BaseType. FullName). GetProperty ("Empty ");
Else
P [0] = e;
// Call
M. Invoke (obj, p );
Return;
}

// Call example.
// Call The onclick of Button1
CallObjectEvent (Button1, "OnClick ");
// Call the OnKeyPress of Button5
CallObjectEvent (Button5, "OnKeyPress ");
// Call OnTextChanged of Text1
CallObjectEvent (Text1, "OnTextChanged ");
// Call the Form KeyPress event. this is the winform and the Enter key.
CallObjectEvent (this, "OnKeyPress", new KeyPressEventArgs (char) 13 ));

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.