如何在 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 好听的元旦简短祝福语