如何在 C# 中声明一个事件?
事件是用户操作,例如按键、点击、鼠标移动等,或某些事件,例如系统生成的通知。
事件在类中声明和引发,并使用同一类或其他类中的委托与事件处理程序相关联。包含事件的类用于发布事件。
要在类中声明事件,首先必须声明该事件的委托类型。例如,
public delegate string myDelegate(string str);
现在,声明一个事件-
event myDelegate newEvent;
让我们看一个在C#中处理事件的例子-
示例
using System;
namespace Demo {
public delegate string myDelegate(string str);
class EventProgram {
event myDelegate newEvent;
public EventProgram() {
this.newEvent += new myDelegate(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = obj1.newEvent("我的网站!");
Console.WriteLine(result);
}
}
}输出结果Welcome 我的网站!
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短