[Reading notes] C# study notes two: the usage and differences of delegates and events.


[Reading notes] C# study notes two: the usage and differences of delegates and events.


Foreword: 

What is C# delegate                                                                                                                                                                                              

The delegation in c# can be understood as a wrapper of the function, which allows the function in C# to be passed as a parameter, which is equivalent to the function pointer in C++. C++ uses the function pointer to obtain the entry address of the function, and then through this Pointer to realize the operation of the function.

The definition of a delegate is similar to the definition of a method, except that a delegate keyword is added before the definition.

 

text:


A delegate can be regarded as a higher-level pointer. It can not only pass the address to another function, but also pass multiple information such as parameters and return values.
The system also automatically generates synchronous and asynchronous invocation methods for delegated objects. Developers can use BeginInvoke and EndInvoke methods to abandon Thread and directly use multi-threaded invocation.

 

1. Delegating
IL analysis shows that Delegate inherits from the System.MulticastDelegate class and automatically generates three common methods: BeginInvoke, EndInvoke, and Invoke.

The Invoke method is used to call the corresponding method of the delegate object synchronously, while BeginInvoke and EndInvoke are used to call the corresponding method in an asynchronous manner.

1.1 Simple delegation
When establishing a delegate object, the parameter type of the delegate must correspond to the delegate method. As long as the method name example.Method is entered into the constructor of the delegate object, the delegate will be straightforward

Then bind this method.
Using myDelegate.Invoke(string message), you can call the delegate method explicitly.
But in the actual operation, we don't need to use the Invoke method, but as long as you directly use myDelegate(string message), you can call the delegate method.

Copy code

 1 class Program 2 { 3     void MyDelegate(string message); 4  5     public class Example 6     { 7         public void Method(string message) 8         { 9             MessageBox.Show(message);10         }11     }12 13     static void Main(string[] args)14     {15         Example example=new Example();16         MyDelegate myDelegate=new MyDelegate(example.Method);17         myDelegate("Hello World");18         Console.ReadKey();19     }20 }

Copy code

 

1.2 Commission with return value

When creating a delegate object, the return value of the delegate must correspond to the delegate method. Using the example below, the method will return "Hello Leslie".

Copy code

 1 class Program 2 { 3     delegate string MyDelegate(string message); 4  5     public class Example 6     { 7         public string Method(string name) 8         { 9             return "Hello " + name;10         }11     }12 13     static void Main(string[] args)14     {15         Example example=new Example();16         //绑定委托方法17         MyDelegate myDelegate=new MyDelegate(example.Method);18         //调用委托,获取返回值19         string message = myDelegate("Leslie");20         Console.WriteLine(message);21         Console.ReadKey();22     }23 }

Copy code

 

1.3 多路广播委托
在上面提过,委托类继承于MulticastDelegate,这使委托对象支持多路广播,即委托对象可以绑定多个方法。
当输入参数后,每个方法会按顺序进行迭代处理,并返回最后一个方法的计算结果。
下面的例子中,Price 类中有两个计算方法,Ordinary 按普通的9.5折计算,Favourable 按优惠价 8.5 折计算。
委托同时绑定了这两个方法,在输入参数100以后,Ordinary、Favourable这两个方法将按顺序迭代执行下去,最后返回 Favourable 方法的

计算结果 85。

Copy code

 1 delegate double MyDelegate(double message); 2 public class Price 3 { 4     public double Ordinary(double price) 5     { 6         double price1 = 0.95 * price; 7         Console.WriteLine("Ordinary Price : "+price1); 8         return price1; 9     }10 11     public double Favourable(double price)12     {13         double price1 = 0.85 * price;14         Console.WriteLine("Favourable Price : " + price1);15         return price1;16     }17 18     static void Main(string[] args)19     {20         Price price = new Price();21         //绑定Ordinary方法22         MyDelegate myDelegate = new MyDelegate(price.Ordinary);23         //绑定Favourable方法24         myDelegate += new MyDelegate(price.Favourable);25         //调用委托26         Console.WriteLine("Current Price : " + myDelegate(100));27         Console.ReadKey();28     }29 }

Copy code

 

1.4 Observer模式中的事件与委托 

Copy code

 1 class Program 2 { 3     public delegate void ObserverDelegate(); 4      5     static void Main(string[] args) 6     { 7         // 具体主题角色通常用具体自来来实现 8         ConcreteSubject subject = new ConcreteSubject(); 9 10         //传入的只是观察者的通过方法。11         subject.Attach(new ConcreteObserver(subject, "Observer A").Update);12         subject.Attach(new ConcreteObserver(subject, "Observer B").Update);13         subject.Attach(new ConcreteObserver(subject, "Observer C").Update);14 15         subject.SubjectState = "Ready";16         subject.Notify();17 18         Console.Read();19     }20 21 22     //抽象主体类23     public abstract class Subject24     {25         public ObserverDelegate observerDelegate;26 27         //增加观察者28         public void Attach(ObserverDelegate observer)29         {30             observerDelegate += observer;31         }32 33         //移除观察者34         public void Remove(ObserverDelegate observer)35         {36             observerDelegate -= observer;37         }38 39         //像观察者发通知40         public void Notify()41         { 
42             if (observerDelegate != null)43             {44                 observerDelegate();45             }46         }47     }48 49     //具体主题类50     public class ConcreteSubject : Subject51     {52         public string SubjectState { get; set; }53     }54 55     //具体观察者56     public class ConcreteObserver57     {58         private string observerState;59         private string name;60         private ConcreteSubject subject;61 62         public ConcreteObserver(ConcreteSubject subject, string name)63         {64             this.subject = subject;65             this.name = name;66         }67 68         //实现抽象观察者中的更新操作69         public void Update()70         {71             observerState = subject.SubjectState;72             Console.WriteLine("The observer's state of {0} is {1}", name, observerState);73         }74     }75 }

Copy code

 

Second, event


(1) Encapsulation of delegation during the event can be understood as a special delegation.
(2) In the event, there are actually two methods (namely add_event() and remove_event()) and a private delegate variable. These two methods are used to enter the private delegate variable.

The merging and removal of lines, when the += of the event is called, it is actually the add_event() method in the called event, and the same -= is calling the remove_event() method
(3) The event can only add new response methods from outside the object And delete the known response methods, but can not actively trigger events and obtain other registered response methods and other information. If using

Public delegates cannot make these restrictions, which means that events restrict delegates, making delegates more convenient to use.
Some people also say that the event is the castration of the commission, which is probably the same.

There is not much explanation about the event here. I saw a good blog post about the event. I recommend you to read it: http://www.cnblogs.com/landeanfen/p/4721525.html

PS: This blog is just to record your own learning gains. As the saying goes, a good memory is not as good as a bad pen. I hope I can stick to it. 

Category:  C# basic seriesreading notes

Good article should  pay attention to my  favorite article  

Is a flower considered romantic


Guess you like

Origin blog.51cto.com/7592962/2543851