今天来介绍一下delegate和event。delegate在c#中可以定义一个函数类型,可以将函数作为一个对象来使用。event在c#中则可以看做一个函数的集合,event中包含了一个或多个函数。
delegate
using system;
public class myclass
{
//定义委托
public delegate void eventhandler(string pparameter);
//委托对象
public eventhandler handler = null;
public void main()
{
handler = testfunction;
handler("hello world");
}
private void testfunction(string pparameter)
{
console.writeline("pparameter is " + pparameter);
}
}
如上代码,定义委托关键字“delegate”,委托的定义包含委托返回值、委托名称、委托参数。定义了委托类型之后,就可以声明委托对象了。eventhandler就是定义的委托类型,handler则是声明的委托对象。
在使用过程中就可以将函数testfunction赋值给handler,这里需要注意的是委托的返回值和参数必须和赋值函数的返回值和参数一致,否则编译器则会提示错误。在使用时像普通的函数调用一样使用即可。
event
using system;
public class myclass
{
public delegate void eventhandler(string pparameter);
public event eventhandler handler = null;
public void main()
{
handler += helloworld;
handler += goodmorning;
handler("");
handler -= goodmorning;
handler?.invoke("");
/*输出结果
* this is helloworld
* this is goodmorning
* this is helloworld
*/
}
private void helloworld(string pparameter)
{
console.writeline("this is helloworld");
}
private void goodmorning(string pparameter)
{
console.writeline("this is goodmorning");
}
}
如上代码,使用关键字“event”来定义事件,这里的handler已经不是委托对象了,而是事件对象,事件的类型依然是委托类型。和委托对象不同,事件对象可以包含多个函数,通过+=运算符来进行添加函数。如果需要从事件中去除某个函数,则可以通过-=运算符来移除函数。
事件除了可以像普通函数一样通过()括号的方式调用,也可以通过invoke方法进行调用。作者个人比较喜欢用invoke方法进行调用,这样可以使用条件运算符“?”来进行判断事件是否为空。
官方文档连接
delegate文档连接:https://learn.microsoft.com/zh-cn/dotnet/csharp/delegate-class
发表评论