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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短