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 生日广州男生祝福语简短