C # delegate, Proxy
Examples are as follows
The Show method of B is bound to the show method of a, making a at show Time B also show
Delegate agent usage in C #
- Defines the delegate object type, such as:
public delegate void MyEventHandler (object sender, EventArgs e);
Where sender represents the trigger event itself, EventArgs is the event argument class
- Define the event argument class, this can be done or not, see the requirements, if you need to pass some information, you can extend the EventArgs class, such as
Public myeventargs:eventargs{/ Here you can define some required variables, and methods /}
You should automatically go back to styling when you pass in. (Will you? Yes, I've tried it myself)
- The event object is defined with the Events keyword, which is also a delegate object that binds to the object of the class at bind time (this object is an event and a delegate, that is, it contains whether the event is bound)
public event MyEventHandler Show;
- The method to be bound, that is, the show definition of B here and the delegate object in 1 have the same parameters and return value type (here if the EventArgs class is extended, the notation in B is arbitrary, anyway can be traced back to the shape, well, I tried) such as:
public void Show (object sender, Evnetargs e) {/TODO/}
- binding, the way to bind is to the current show object + = For example:
This.show + = new MyEventHandler ((New B ()). Show);
The question here is where to bind, can bind in a, pass in B or create a new B like this can also be bound in B, in B to pass in a or new A, the problem is that the code can go to the binding;
- Write A's trigger event show, and call delegate in show
public void OnShow(){
if(this.show!=null)//判断是否绑定了方法,如果绑定了那就执行呗;
this.show(this,new EventArgs());
}
- The whole process is finished, and now it's the onshow that triggers a.
Refer to the post of the cold flying rain
At the same time attach a piece of comparative understood code modified from the above author
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate {
// 扩展EventArgs 如果不需要可以不用
public class myEventArgs:EventArgs{
public int k= 10;
}
class Dog {
public Dog(){
Host host = new Host();
this.Alarm += new AlarmEventHandler(host.hostEventHandler);
}
//delegate
public delegate void AlarmEventHandler(object sender , myEventArgs e);
//event
public event AlarmEventHandler Alarm;
// yinfa shijian de hanshu
public void OnAlarm(){
Console.WriteLine("dog Aalrt");
if(this.Alarm!=null){
this.Alarm(this,new myEventArgs());
}
}
}
class Host{
public void hostEventHandler(object sender,EventArgs e){
Console.WriteLine("Host konwn");
// Console.WriteLine(((myEventArgs)e).k);//扩展EventArgs后
/*DOTO*/
}
}
class Delegate{
public static void Main(String []args){
Dog dog = new Dog();
dog.OnAlarm();
Console.ReadKey();
}
}
}
Markdown copy of the past there will be a line number, crouching Groove metrorrhagia;
From for notes (Wiz)
C # Delegate Agent