# 委托 事件的深入

  • 事件触发者被抽象出来,称为消息发布者,event() 事件触发和提供参数
  • 事件接受都被抽象出来,称为消息订阅者,event+func 提供方法

# 委托事件补充:

public  EventHandler AfterChangeEvent { get; set; }
public event  EventHandler AfterChangeEvent { get; set; }
1.都是一个实例对象,但一个是委托的实例,一个是事件
2.加了event  只能由event  所在的类触发该事件。
3.+= 添加触发事件,其他地方都可以添加,但是在哪个类触发,便只触发该类的添加事件,
事件,委托都一样。
public delegate void EventHandler(object sender, EventArgs e);//这是委托的类,而非实例
1
2
3
4
5
6
7

先回顾委托和事件

# 委托

# 1.委托基础
public delegate void mydelegate();        
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    mydelegate my = new mydelegate(Myfun);
    my.Invoke();
}
public void Myfun()
{
    Console.WriteLine("123456");
}
1
2
3
4
5
6
7
8
9
10
11
# 2.委托基础+lamdal表达式
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    mydelegate md = () => { Console.WriteLine("123456"); };
    md ?.Invoke();
    mydelegate my = new mydelegate(()=> {
    Console.WriteLine("123456");
    });
    my?.Invoke();
}
1
2
3
4
5
6
7
8
9
10
# 3.action和func
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    Action<int> action = new Action<int>(Myaction);
    Action<int> action1 = new Action<int>((num)=> { Console.WriteLine(num.ToString()); });
    Func<int, string> func = new Func<int, string>(Myfunc);
    Func<int, string> func1 = new Func<int, string>((num) => { return num.ToString(); });
}
1
2
3
4
5
6
7
8
# 4.多播委托
public void Myaction(int num)
{
    Console.WriteLine(num.ToString());
}

public string Myfunc(int num)
{
    return num.ToString();
}

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    Action<int> action = new Action<int>(My1);
    action += My2;
    action += (num) => { global::System.Console.WriteLine(num+2); };
    action -= My2;
    action.Invoke(1);
}

public void My1(int num)
{
    Console.WriteLine(num.ToString());
}

public void My2(int num)
{
    Console.WriteLine((num+1).ToString());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# 事件+event

窗口1
public  delegate void  mydelegate();
public partial class Form1 : Form
{
    public event mydelegate my;
    public event Action Action ;
    public event EventHandler Event;
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        Test();
    }
}
窗口2
public Form2(Form1 form1)
{
    InitializeComponent();
    form1.Test += new Action(() => { Console.WriteLine(123); });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19