Events là hành động người dùng: nhấn phím, click, di chuyển chuột, v.v., hoặc sự kiện hệ thống như thông báo.
Events được khai báo và raise (kích hoạt) trong class, liên kết với event handlers dùng delegates trong cùng class hoặc class khác. Class chứa event dùng để publish event.
Để khai báo event trong class, trước tiên khai báo delegate type cho event. Ví dụ:
public delegate string myDelegate(string str);
Khai báo event:
event myDelegate newEvent;
Ví dụ làm việc với events:
Ví dụ
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);
}
}
}
Kết quả
Welcome My Website!