Truyền khối mã làm tham số ủy quyền trong C #, sử dụng các phương thức Ẩn danh trong C #. Các phương thức ẩn danh là các phương thức không có tên, chỉ có phần thân.
Đây là cách bạn có thể khai báo các phương thức Ẩn danh -
delegate void DemoMethod(int n);
...
DemoMethod dm = delegate(int a) {
Console.WriteLine("Our Anonymous Method: {0}", a);
}; Như được hiển thị ở trên, sau đây là phần thân của phương thức ẩn danh -
Console.WriteLine("Our Anonymous Method: {0}", a); Ví dụ
Bạn có thể thử chạy đoạn mã sau để triển khai các phương thức Ẩn danh trong C # -
using System;
delegate void Demo(int n);
namespace MyDelegate {
class TestDelegate {
static int num = 10;
public static void DisplayAdd(int p) {
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void DisplayMult(int q) {
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
Demo dm = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
dm(15);
//instantiating the delegate using the named methods
dm = new Demo(DisplayAdd);
//calling the delegate using the named methods
dm(10);
//instantiating the delegate using another named methods
dm = new Demo(DisplayMult);
//calling the delegate using the named methods
dm(4);
Console.ReadKey();
}
}
} Đầu ra
Anonymous Method: 15 Named Method: 20 Named Method: 80