如何在 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("My Website!");
Console.WriteLine(result);
}
}
}输出
Welcome My Website!
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP