如何在 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 红包祝福语简短10字
18 周六早晨祝福语简短