如何在 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