编程语言
首页 > 编程语言> > C# 委托与事件

C# 委托与事件

作者:互联网

具体流程如下:

1.类外声明委托
public delegate void SaySomething(string name);

2.写方法

public void SayHello(string name) { Console.WriteLine(“Hello,” + name + “!”); }
public void SayNiceToMeetYou(string name) { Console.WriteLine(“Nice to meet you,” + name + “!”); }

3.声明事件
public event SaySomething come;
//SaySomething是委托名,come是事件名。

4.实例化委托,并将方法赋给事件(用+=)
public void test()
{
SaySomething sayhello = new SaySomething(SayHello);
SaySomething saynice = new SaySomething(SayNiceToMeetYou); come += sayhello;
come += saynice;
come(“张三”); //用事件去调用所有委托的方法
}
在这里插入图片描述

标签:name,委托,C#,void,SaySomething,事件,come,public,string
来源: https://blog.csdn.net/gong56/article/details/122678585