Recently, I entrusted the following small explanation, because she went to Baidu and I aimed at it again. Shenma "commissioned the secret" and "holy field 」, I rely on events for half a day.
A delegate is a method pointer, which is strongly typed (C # is strongly typed ).
The delegate can be opposite, and the parameter can also have a return value. Events are unidirectional,
The method signature parameter specifies the object and EventArgs (or its subclass), and the return parameter specifies the void without the return value.
The Code is as follows:
1 using System;
2
3 namespace DelegateTutorial
4 {
5 /////////////////////////////////////// ////
6
7 public delegate string Method ();
8
9 /////////////////////////////////////// ////
10
11 public class ClassWithDelegate
12 {
13 public Method methodPointer;
14
15 public void print ()
16 {
17 Console. WriteLine (methodPointer (); // The method has no entity here
18}
19}
20
21 /////////////////////////////////////// ////
22
23 class Program
24 {
25 public static void Main ()
26 {
27 ClassWithDelegate myClass = new ClassWithDelegate ();
28
29 myClass. methodPointer = MethodA; // the token is materialized here. Use the method pointer to understand the delegate. I like to write it like this.
30 // the above Code also works: myClass. methodPointer = new Method (MethodA );
31 myClass. print ();
32
33 myClass. methodPointer = MethodB;
34 myClass. print ();
35
36 Console. ReadKey ();
37}
38
39 public static string MethodA ()
40 {
41 return "Method .";
42}
43
44 private static string MethodB ()
45 {
46 return "Method B .";
47}
48}
49}
You do not need to use protected virtual, or you can change the behavior at runtime. Let's take a look at the instance and use it as Callback (for details, see Bill Wagner, valid tive C # (Addison-Wesley, 2005), p.129-131 ):
1 public delegate bool CancelProcess ();
2
3 /// <summary>
4 // material master data list
5 /// </summary>
6 public class ItemMasterRecords: Collection <ItemRecords>
7 {
8 // omitted ....
9
10 ValidationErrors validationErrors;
11
12 /// <summary>
13 // verify all data
14 /// </summary>
15 /// <param name = "isContinue"> return the delegation method of the canceled action of bool. </param>
16 public void validateItemMasterRecords (CancelProcess isCancel)
17 {
18 bool _ isCancel = false;
19 foreach (ItemRecords item in this)
20 {
21 item. validate (validationErrors); // Method for verifying a single item
22
23 foreach (CancelProcess ptr in isCancel. GetInvocationList ())
24 // No problem with sending cancellation instructions in multiple locations
25 {
26 _ isCancel | = ptr ();
27 if (_ isCancel)
28 {
29 this. validationErrors. Clear ();
30 return;
31}
32}
33}
34
35}
36}