Linh Ngo
Nodejs developer. Working in a tech education company - Techmastervn with a vision to promote STEM and provide valuable as well as affordable IT training to students and young adults
class Program
{
// khai báo 1 delegate
public delegate int Calculate (int a, int b);
} class Program
{
// kháo báo 1 delegate
public delegate int Calculate (int a, int b);
static void Main(string[] args)
{
// delegate Calculate tham chiếu hay trỏ đến phương thức Add
Calculate calculateDel = Add;
calculateDel(10, 4); // 14
// delegate Calculate tham chiếu hay trỏ đến phương thức Subtract
calculateDel = Subtract;
Console.WriteLine(calculateDel.Invoke(10, 4)); // 6
}
// khai báo 2 phương thức Add, Subtract
// có cùng kiểu (method signature) với delegate
public static int Add (int a, int b)
{
return a + b;
}
public static int Subtract (int a, int b)
{
return a - b;
}
} class Program {
// kháo báo 1 delegate
public delegate int Calculate (int a, int b);
static void Main (string[] args) {
// delegate Calculate tham chiếu hay trỏ đến phương thức Add
Calculate calculateDel = Add;
Console.WriteLine (calculateDel (10, 4)); // 14
// delegate Calculate tham chiếu hay trỏ đến phương thức Subtract
calculateDel = Subtract;
Console.WriteLine (calculateDel (10, 4)); // 6
// truyền phương thức là tham số đầu vào
CalculateHelper (Add, 10, 4);
}
// Tạo 1 phương thức nhận delegate là tham số đầu vào
public static void CalculateHelper (Calculate del, int a, int b) {
Console.WriteLine (del (a, b));
}
// khai báo 2 phương thức Add, Subtract
// có cùng kiểu (method signature) với delegate
public static int Add (int a, int b) {
return a + b;
}
public static int Subtract (int a, int b) {
return a - b;
}
} class Program {
// kháo báo 1 delegate
public delegate int Calculate (int a, int b);
static void Main (string[] args) {
// Multicast - viết đè lên kết quả của các delegates trước
// Console.WriteLine(calculateDel2(9, 10)); // chỉ -1 đc in ra
// Để xem tất cả kết quả
Console.WriteLine("Multicast del: ");
foreach (Calculate del in calculateDel2.GetInvocationList())
{
Console.WriteLine(del(9, 10));
}
}
// Tạo 1 phương thức nhận delegate là tham số đầu vào
public static void CalculateHelper (Calculate del, int a, int b) {
Console.WriteLine (del (a, b));
}
// khai báo 2 phương thức Add, Subtract
// có cùng kiểu (method signature) với delegate
public static int Add (int a, int b) {
return a + b;
}
public static int Subtract (int a, int b) {
return a - b;
}
} class Program
{
// khai báo 1 delegate
// thường khai báo event ngay sau delegate nó sẽ dùng
}By Linh Ngo