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