Delegate là khái niệm trong C#, nó giống như con trỏ hàm của C++. Delegate là con trỏ trỏ vào các hàm có cùng đối(số lượng đối và kiểu đối giống nhau).
Late Binding Delegates: A delegate is a repository of type-safe function pointers.
Ví dụ:
Khai báo Lớp Hello
Late Binding Delegates: A delegate is a repository of type-safe function pointers.
Ví dụ:
Khai báo Lớp Hello
class Hello
{
public static void ChaoBan()
{
Console.WriteLine("Chao ca nha");
}
public static void ChaoBan(string s)
{
Console.WriteLine("Chào {0}",s);
}
}
Khai báo Hàm Delegatepublic delegate void Write(); public delegate void WriteS(string s);Cách sử dụng hàm Deleagate:
var myDelegate = new MyClassWithDelegate.Write(Hello.ChaoBan);
var myDelegateS = new MyClassWithDelegate.WriteS(Hello.ChaoBan);
myDelegate();
myDelegateS("Ban No");//Nếu bạn không truyền tham số sẽ báo lỗi
Lưu ý: Bạn có thể dùng hàm Invoke trong delegatemyDelegateS.Invoke("Bạn T");
Còn ý nghĩa của nó thế nào thì mình không biết. (Nó lấy đặc điểm của hàm ủy thác để sử dụng).
Nhận xét
Đăng nhận xét