Trang chủ
Bài viết mới
Diễn đàn
Bài mới trên hồ sơ
Hoạt động mới nhất
VIDEO
Mùa Tết
Văn Học Trẻ
Văn Học News
Media
New media
New comments
Search media
Đại Học
Đại cương
Chuyên ngành
Triết học
Kinh tế
KHXH & NV
Công nghệ thông tin
Khoa học kĩ thuật
Luận văn, tiểu luận
Phổ Thông
Lớp 12
Ngữ văn 12
Lớp 11
Ngữ văn 11
Lớp 10
Ngữ văn 10
LỚP 9
Ngữ văn 9
Lớp 8
Ngữ văn 8
Lớp 7
Ngữ văn 7
Lớp 6
Ngữ văn 6
Tiểu học
Thành viên
Thành viên trực tuyến
Bài mới trên hồ sơ
Tìm trong hồ sơ cá nhân
Credits
Transactions
Xu: 0
Đăng nhập
Đăng ký
Có gì mới?
Tìm kiếm
Tìm kiếm
Chỉ tìm trong tiêu đề
Bởi:
Hoạt động mới nhất
Đăng ký
Menu
Đăng nhập
Đăng ký
Install the app
Cài đặt
Chào mừng Bạn tham gia Diễn Đàn VNKienThuc.com -
Định hướng Forum
Kiến Thức
- HÃY TẠO CHỦ ĐỀ KIẾN THỨC HỮU ÍCH VÀ CÙNG NHAU THẢO LUẬN Kết nối:
VNK X
-
VNK groups
| Nhà Tài Trợ:
BhnongFood X
-
Bhnong groups
-
Đặt mua Bánh Bhnong
CÔNG NGHỆ
Công Nghệ Thông Tin
Code
Tìm hiểu về Delegate trong C#
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Trả lời chủ đề
Nội dung
<blockquote data-quote="uocmo_kchodoi" data-source="post: 177601" data-attributes="member: 165510"><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Trong tiếng Việt,</span><a href="https://vnkienthuc.com/forums/code.377/" target="_blank"> <span style="color: rgb(41, 105, 176)">delegate</span></a><span style="color: rgb(41, 105, 176)"> đ</span><span style="color: rgb(0, 0, 0)">ược dịch là “ủy nhiệm hàm”, tuy nhiên mọi người đều không sử dụng từ này mà gọi bằng tên gốc là delegate. Delegate tương tự như con trỏ hàm trong C++. Nó được sử dụng để triển khai các sự kiện và các phương thức call-back. Tất cả delegate được kế thừa một cách ngầm định từ lớp System</span><span style="color: rgb(41, 105, 176)"><a href="https://vnkienthuc.com/forums/cong-nghe-thong-tin.375/" target="_blank">.Delegate trong C#</a>.</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Một delegate giống như một “người đại diện” hay “đại sứ”. Một delegate có thể được dùng để tạo một bao đóng (encapsulation) cho bất kì phương thức nào, miễn là nó phù hợp (kiểu trả về, tham số). Là một “đại sứ”, delegate có thể triệu gọi phương thức bất kì nơi nào: từ đối tượng này đến đối tượng kia, từ thread này sang thread kia,… Đây là đặc điểm chính của delegate, bạn sẽ cần nhớ lại điều này khi giải quyết các vấn đề thường gặp như truyền dữ liệu giữa hai Form, xử lý lỗi “Cross-thread operation not valid”, tạo event, …</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Ngoài ra, bởi vì là một đối tượng, delegate có thể được truyền vào làm tham số của các phương thức. Bạn có thể hiểu đơn giản: delegate là một đối tượng dùng để bao đóng một hoặc nhiều phương thức (Multicast), hay có thể coi delegate là một sự kết hợp giữa đối tượng và phương thức.</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: #0000ff"><strong>1. Khai báo Delegate trong C#</strong></span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Khai báo Delegate trong C# quyết định các phương thức mà có thể được tham chiếu bởi Delegate đó. Một Delegate có thể tham chiếu tới một phương thức, mà có cùng dấu hiệu như của Delegate đó.</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Ví dụ, xét một delegate sau đây:</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">public delegate int MyDelegate (string s);</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Delegate trên có thể được sử dụng để tham chiếu bất kỳ phương thức mà có một tham số<em>string</em> đơn và trả về một biến kiểu <em>int</em>.</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Cú pháp để khai báo delegate trong C# là:</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">delegate <kiểu_trả_về> <tên_delegate> <danh_sách_tham_số></span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: #0000ff"><strong>2. Khởi tạo Delegate trong C#</strong></span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Khi một kiểu delegate được khai báo, một đối tượng delegate phải được tạo với từ khóa new và được liên kết với một phương thức cụ thể. Khi tạo một delegate, tham số được truyền tới biểu thức new được viết tương tự như một lời gọi phương thức, nhưng không có tham số tới phương thức đó. Ví dụ:</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">public delegate void printString(string s);</span></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">...</span></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">printString ps1 = new printString(WriteToScreen);</span></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">printString ps2 = new printString(WriteToFile);</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Ví dụ sau minh họa cách khai báo, </span><span style="color: rgb(61, 142, 185)"><a href="https://vnkienthuc.com/forums/hoi-dap-tin-hoc.378/" target="_blank">khởi tạo và sử dụng một delegate</a></span><span style="color: rgb(0, 0, 0)"> mà có thể được sử dụng để tham chiếu các phương thức mà nhận một tham số integer và trả về một giá trị integer.</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">using System;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">delegate int NumberChanger(int n);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">namespace VietJackCsharp</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">{</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> class TestCsharp</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> static int num = 10;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public static int AddNum(int p)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> num += p;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> return num;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public static int MultNum(int q)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> num *= q;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> return num;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public static int getNum()</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> return num;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> static void Main(string[] args)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("Vi du minh hoa Delegate trong C#");</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("----------------------------------");</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> //tao cac doi tuong delegate</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> NumberChanger nc1 = new NumberChanger(AddNum);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> NumberChanger nc2 = new NumberChanger(MultNum);</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> //goi cac phuong thuc boi su dung cac doi tuong delegate</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> nc1(25);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("Gia tri cua num la: {0}", getNum());</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> nc2(5);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("Gia tri cua num la: {0}", getNum());</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.ReadKey();</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">}</span></em></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Nếu bạn không sử dụng lệnh Console.ReadKey(); thì chương trình sẽ chạy và kết thúc luôn (nhanh quá đến nỗi bạn không kịp nhìn kết quả). Lệnh này cho phép chúng ta nhìn kết quả một cách rõ ràng hơn.</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Biên dịch và chạy chương trình C# trên sẽ cho kết quả sau:</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"></span></p><p style="text-align: center"><span style="font-size: 18px"><img src="https://vietjack.com/csharp/images/delegate.PNG" alt="" class="fr-fic fr-dii fr-draggable " data-size="" style="" /></span></p><p></p><p style="text-align: center"></p><p><span style="font-size: 18px"><span style="color: #0000ff"><strong>3. Multicast một Delegate trong C#</strong></span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Các đối tượng Delegate có thể được hợp thành bởi sử dụng toán tử "+". Một delegate được hợp thành gọi hai Delegate mà nó được hợp thành từ đó. Chỉ có các delegate cùng kiểu có thể được hợp thành. Toán tử "-" có thể được sử dụng để gỡ bỏ một delegate thành phần từ một delegate được hợp thành.</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Sử dụng thuộc tính này của các delegate, bạn có thể tạo một danh sách triệu hồi của các phương thức mà sẽ được gọi khi delegate đó được triệu hồi. Điều này được gọi làMulticasting của một Delegate. Chương trình ví dụ sau minh họa </span><span style="color: rgb(61, 142, 185)"><a href="https://vnkienthuc.com/threads/tim-hieu-ve-collection-trong-c.77358/" target="_blank">Multicasting</a> </span><span style="color: rgb(0, 0, 0)">của một Delegate trong C#:</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">using System;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">delegate int NumberChanger(int n);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">namespace VietJackCsharp</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">{</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> class TestCsharp</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> static int num = 10;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public static int AddNum(int p)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> num += p;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> return num;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public static int MultNum(int q)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> num *= q;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> return num;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public static int getNum()</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> return num;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> static void Main(string[] args)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("Vi du minh hoa Delegate trong C#");</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("----------------------------------");</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> //tao cac doi tuong delegate</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> NumberChanger nc;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> NumberChanger nc1 = new NumberChanger(AddNum);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> NumberChanger nc2 = new NumberChanger(MultNum);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> nc = nc1;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> nc += nc2;</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> //goi multicast</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> nc(5);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("Gia tri cua num la: {0}", getNum());</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.ReadKey();</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">}</span></em></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Biên dịch và chạy chương trình C# trên sẽ cho kết quả sau:</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"></span></p><p style="text-align: center"><span style="font-size: 18px"><img src="https://vietjack.com/csharp/images/delegate-1.PNG" alt="" class="fr-fic fr-dii fr-draggable " data-size="" style="" /></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: #0000ff"><strong>4. Cách sử dụng Delegate trong C#</strong></span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Ví dụ sau minh họa cách sử dụng của delegate trong C#. Delegate với tên <em>printString</em> có thể được sử dụng để tham chiếu phương thức mà nhận một chuỗi như là input và không trả về cái gì.</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Chúng ta sử dụng delegate này để gọi hai phương thức: phương thức đầu tiên in chuỗi tới Console, và phương thức thứ hai in nó tới một File.</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">using System;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">using System.IO;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">namespace VietJackCsharp</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">{</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> class TestCsharp</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> static FileStream fs;</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> static StreamWriter sw;</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> // khai bao delegate</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public delegate void printString(string s);</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> // phuong thuc de in tren console</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public static void WriteToScreen(string str)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("Chuoi la: {0}", str);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> //phuong thuc nay de ghi du lieu vao file</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public static void WriteToFile(string s)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> fs = new FileStream("c:\\message.txt",</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> FileMode.Append, FileAccess.Write);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> sw = new StreamWriter(fs);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> sw.WriteLine(s);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> sw.Flush();</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> sw.Close();</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> fs.Close();</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> // phuong thuc nay nhan delegate lam tham so va su dung no de</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> // goi cac phuong thuc neu can</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> public static void sendString(printString ps)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> ps("Hoc C# co ban va nang cao tai VietJack");</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> static void Main(string[] args)</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> {</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("Vi du minh hoa Delegate trong C#");</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.WriteLine("----------------------------------");</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> </span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> printString ps1 = new printString(WriteToScreen);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> printString ps2 = new printString(WriteToFile);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> sendString(ps1);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> sendString(ps2);</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> Console.ReadKey();</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3"> }</span></em></span></p><p><span style="font-size: 18px"><em><span style="color: #5900b3">}</span></em></span></p><p><span style="font-size: 18px"><span style="color: rgb(0, 0, 0)">Biên dịch và chạy chương trình C# trên sẽ cho kết quả sau:</span></span></p><p><span style="font-size: 18px"></span></p><p><span style="font-size: 18px"></span></p><p style="text-align: center"><span style="font-size: 18px"><img src="https://vietjack.com/csharp/images/delegate-2.PNG" alt="" class="fr-fic fr-dii fr-draggable " data-size="" style="" /></span></p><p></p><p style="text-align: center"></p><p><span style="font-size: 18px">Mặc dù bạn có thể cho rằng delegate không cần thiết và tránh sử dụng nó (một cách trực tiếp) nhưng cuối cùng bạn vẫn phải nhận thấy rằng: mình không thể “sống” khi thiếu delegate. Delegate không khó hiểu cũng như không khó để áp dụng, nếu bạn dành một chút thời gian nghiên cứu. Chúc các bạn thành công!</span></p><p><span style="font-size: 18px"></span></p><p style="text-align: right"><span style="font-size: 18px"><span style="color: #000000">Nguồn: vietjack.com</span></span></p></blockquote><p></p>
[QUOTE="uocmo_kchodoi, post: 177601, member: 165510"] [COLOR=#000000][B][SIZE=5] [/SIZE][/B][/COLOR][SIZE=5][COLOR=rgb(0, 0, 0)]Trong tiếng Việt,[/COLOR][URL='https://vnkienthuc.com/forums/code.377/'][COLOR=rgb(0, 0, 0)] [/COLOR][COLOR=rgb(41, 105, 176)]delegate[/COLOR][/URL][COLOR=rgb(41, 105, 176)] đ[/COLOR][COLOR=rgb(0, 0, 0)]ược dịch là “ủy nhiệm hàm”, tuy nhiên mọi người đều không sử dụng từ này mà gọi bằng tên gốc là delegate. Delegate tương tự như con trỏ hàm trong C++. Nó được sử dụng để triển khai các sự kiện và các phương thức call-back. Tất cả delegate được kế thừa một cách ngầm định từ lớp System[/COLOR][COLOR=rgb(41, 105, 176)][URL='https://vnkienthuc.com/forums/cong-nghe-thong-tin.375/'].Delegate trong C#[/URL].[/COLOR] [COLOR=rgb(0, 0, 0)]Một delegate giống như một “người đại diện” hay “đại sứ”. Một delegate có thể được dùng để tạo một bao đóng (encapsulation) cho bất kì phương thức nào, miễn là nó phù hợp (kiểu trả về, tham số). Là một “đại sứ”, delegate có thể triệu gọi phương thức bất kì nơi nào: từ đối tượng này đến đối tượng kia, từ thread này sang thread kia,… Đây là đặc điểm chính của delegate, bạn sẽ cần nhớ lại điều này khi giải quyết các vấn đề thường gặp như truyền dữ liệu giữa hai Form, xử lý lỗi “Cross-thread operation not valid”, tạo event, …[/COLOR] [COLOR=rgb(0, 0, 0)]Ngoài ra, bởi vì là một đối tượng, delegate có thể được truyền vào làm tham số của các phương thức. Bạn có thể hiểu đơn giản: delegate là một đối tượng dùng để bao đóng một hoặc nhiều phương thức (Multicast), hay có thể coi delegate là một sự kết hợp giữa đối tượng và phương thức.[/COLOR] [COLOR=#0000ff][B]1. Khai báo Delegate trong C#[/B][/COLOR] [COLOR=rgb(0, 0, 0)]Khai báo Delegate trong C# quyết định các phương thức mà có thể được tham chiếu bởi Delegate đó. Một Delegate có thể tham chiếu tới một phương thức, mà có cùng dấu hiệu như của Delegate đó.[/COLOR] [COLOR=rgb(0, 0, 0)]Ví dụ, xét một delegate sau đây:[/COLOR] [COLOR=rgb(0, 0, 0)]public delegate int MyDelegate (string s);[/COLOR] [COLOR=rgb(0, 0, 0)]Delegate trên có thể được sử dụng để tham chiếu bất kỳ phương thức mà có một tham số[I]string[/I] đơn và trả về một biến kiểu [I]int[/I].[/COLOR] [COLOR=rgb(0, 0, 0)]Cú pháp để khai báo delegate trong C# là:[/COLOR] [I][COLOR=#5900b3]delegate <kiểu_trả_về> <tên_delegate> <danh_sách_tham_số>[/COLOR][/I] [COLOR=#0000ff][B]2. Khởi tạo Delegate trong C#[/B][/COLOR] [COLOR=rgb(0, 0, 0)]Khi một kiểu delegate được khai báo, một đối tượng delegate phải được tạo với từ khóa new và được liên kết với một phương thức cụ thể. Khi tạo một delegate, tham số được truyền tới biểu thức new được viết tương tự như một lời gọi phương thức, nhưng không có tham số tới phương thức đó. Ví dụ:[/COLOR] [COLOR=rgb(0, 0, 0)]public delegate void printString(string s); ... printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile);[/COLOR] [COLOR=rgb(0, 0, 0)]Ví dụ sau minh họa cách khai báo, [/COLOR][COLOR=rgb(61, 142, 185)][URL='https://vnkienthuc.com/forums/hoi-dap-tin-hoc.378/']khởi tạo và sử dụng một delegate[/URL][/COLOR][COLOR=rgb(0, 0, 0)] mà có thể được sử dụng để tham chiếu các phương thức mà nhận một tham số integer và trả về một giá trị integer.[/COLOR] [I][COLOR=#5900b3]using System;[/COLOR][/I] [I][COLOR=#5900b3]delegate int NumberChanger(int n);[/COLOR][/I] [I][COLOR=#5900b3]namespace VietJackCsharp[/COLOR][/I] [I][COLOR=#5900b3]{[/COLOR][/I] [I][COLOR=#5900b3] class TestCsharp[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] static int num = 10;[/COLOR][/I] [I][COLOR=#5900b3] public static int AddNum(int p)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] num += p;[/COLOR][/I] [I][COLOR=#5900b3] return num;[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] public static int MultNum(int q)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] num *= q;[/COLOR][/I] [I][COLOR=#5900b3] return num;[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] public static int getNum()[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] return num;[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] static void Main(string[] args)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("Vi du minh hoa Delegate trong C#");[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("----------------------------------");[/COLOR][/I] [I][COLOR=#5900b3] //tao cac doi tuong delegate[/COLOR][/I] [I][COLOR=#5900b3] NumberChanger nc1 = new NumberChanger(AddNum);[/COLOR][/I] [I][COLOR=#5900b3] NumberChanger nc2 = new NumberChanger(MultNum);[/COLOR][/I] [I][COLOR=#5900b3] //goi cac phuong thuc boi su dung cac doi tuong delegate[/COLOR][/I] [I][COLOR=#5900b3] nc1(25);[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("Gia tri cua num la: {0}", getNum());[/COLOR][/I] [I][COLOR=#5900b3] nc2(5);[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("Gia tri cua num la: {0}", getNum());[/COLOR][/I] [I][COLOR=#5900b3] Console.ReadKey();[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3]}[/COLOR][/I] [COLOR=rgb(0, 0, 0)]Nếu bạn không sử dụng lệnh Console.ReadKey(); thì chương trình sẽ chạy và kết thúc luôn (nhanh quá đến nỗi bạn không kịp nhìn kết quả). Lệnh này cho phép chúng ta nhìn kết quả một cách rõ ràng hơn.[/COLOR] [COLOR=rgb(0, 0, 0)]Biên dịch và chạy chương trình C# trên sẽ cho kết quả sau:[/COLOR] [/SIZE] [CENTER][SIZE=5][IMG]https://vietjack.com/csharp/images/delegate.PNG[/IMG][/SIZE][/CENTER] [SIZE=5][/SIZE] [CENTER][SIZE=5][/SIZE][/CENTER] [SIZE=5][COLOR=#0000ff][B]3. Multicast một Delegate trong C#[/B][/COLOR] [COLOR=rgb(0, 0, 0)]Các đối tượng Delegate có thể được hợp thành bởi sử dụng toán tử "+". Một delegate được hợp thành gọi hai Delegate mà nó được hợp thành từ đó. Chỉ có các delegate cùng kiểu có thể được hợp thành. Toán tử "-" có thể được sử dụng để gỡ bỏ một delegate thành phần từ một delegate được hợp thành.[/COLOR] [COLOR=rgb(0, 0, 0)]Sử dụng thuộc tính này của các delegate, bạn có thể tạo một danh sách triệu hồi của các phương thức mà sẽ được gọi khi delegate đó được triệu hồi. Điều này được gọi làMulticasting của một Delegate. Chương trình ví dụ sau minh họa [/COLOR][COLOR=rgb(61, 142, 185)][URL='https://vnkienthuc.com/threads/tim-hieu-ve-collection-trong-c.77358/']Multicasting[/URL] [/COLOR][COLOR=rgb(0, 0, 0)]của một Delegate trong C#:[/COLOR] [I][COLOR=#5900b3]using System;[/COLOR][/I] [I][COLOR=#5900b3]delegate int NumberChanger(int n);[/COLOR][/I] [I][COLOR=#5900b3]namespace VietJackCsharp[/COLOR][/I] [I][COLOR=#5900b3]{[/COLOR][/I] [I][COLOR=#5900b3] class TestCsharp[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] static int num = 10;[/COLOR][/I] [I][COLOR=#5900b3] public static int AddNum(int p)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] num += p;[/COLOR][/I] [I][COLOR=#5900b3] return num;[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] public static int MultNum(int q)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] num *= q;[/COLOR][/I] [I][COLOR=#5900b3] return num;[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] public static int getNum()[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] return num;[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] static void Main(string[] args)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("Vi du minh hoa Delegate trong C#");[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("----------------------------------");[/COLOR][/I] [I][COLOR=#5900b3] //tao cac doi tuong delegate[/COLOR][/I] [I][COLOR=#5900b3] NumberChanger nc;[/COLOR][/I] [I][COLOR=#5900b3] NumberChanger nc1 = new NumberChanger(AddNum);[/COLOR][/I] [I][COLOR=#5900b3] NumberChanger nc2 = new NumberChanger(MultNum);[/COLOR][/I] [I][COLOR=#5900b3] nc = nc1;[/COLOR][/I] [I][COLOR=#5900b3] nc += nc2;[/COLOR][/I] [I][COLOR=#5900b3] //goi multicast[/COLOR][/I] [I][COLOR=#5900b3] nc(5);[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("Gia tri cua num la: {0}", getNum());[/COLOR][/I] [I][COLOR=#5900b3] Console.ReadKey();[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3]}[/COLOR][/I] [COLOR=rgb(0, 0, 0)]Biên dịch và chạy chương trình C# trên sẽ cho kết quả sau:[/COLOR] [/SIZE] [CENTER][SIZE=5][IMG]https://vietjack.com/csharp/images/delegate-1.PNG[/IMG][/SIZE][/CENTER] [SIZE=5] [COLOR=#0000ff][B]4. Cách sử dụng Delegate trong C#[/B][/COLOR] [COLOR=rgb(0, 0, 0)]Ví dụ sau minh họa cách sử dụng của delegate trong C#. Delegate với tên [I]printString[/I] có thể được sử dụng để tham chiếu phương thức mà nhận một chuỗi như là input và không trả về cái gì.[/COLOR] [COLOR=rgb(0, 0, 0)]Chúng ta sử dụng delegate này để gọi hai phương thức: phương thức đầu tiên in chuỗi tới Console, và phương thức thứ hai in nó tới một File.[/COLOR] [I][COLOR=#5900b3]using System;[/COLOR][/I] [I][COLOR=#5900b3]using System.IO;[/COLOR][/I] [I][COLOR=#5900b3]namespace VietJackCsharp[/COLOR][/I] [I][COLOR=#5900b3]{[/COLOR][/I] [I][COLOR=#5900b3] class TestCsharp[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] static FileStream fs;[/COLOR][/I] [I][COLOR=#5900b3] static StreamWriter sw;[/COLOR][/I] [I][COLOR=#5900b3] // khai bao delegate[/COLOR][/I] [I][COLOR=#5900b3] public delegate void printString(string s);[/COLOR][/I] [I][COLOR=#5900b3] // phuong thuc de in tren console[/COLOR][/I] [I][COLOR=#5900b3] public static void WriteToScreen(string str)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("Chuoi la: {0}", str);[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] //phuong thuc nay de ghi du lieu vao file[/COLOR][/I] [I][COLOR=#5900b3] public static void WriteToFile(string s)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] fs = new FileStream("c:\\message.txt",[/COLOR][/I] [I][COLOR=#5900b3] FileMode.Append, FileAccess.Write);[/COLOR][/I] [I][COLOR=#5900b3] sw = new StreamWriter(fs);[/COLOR][/I] [I][COLOR=#5900b3] sw.WriteLine(s);[/COLOR][/I] [I][COLOR=#5900b3] sw.Flush();[/COLOR][/I] [I][COLOR=#5900b3] sw.Close();[/COLOR][/I] [I][COLOR=#5900b3] fs.Close();[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] // phuong thuc nay nhan delegate lam tham so va su dung no de[/COLOR][/I] [I][COLOR=#5900b3] // goi cac phuong thuc neu can[/COLOR][/I] [I][COLOR=#5900b3] public static void sendString(printString ps)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] ps("Hoc C# co ban va nang cao tai VietJack");[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] static void Main(string[] args)[/COLOR][/I] [I][COLOR=#5900b3] {[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("Vi du minh hoa Delegate trong C#");[/COLOR][/I] [I][COLOR=#5900b3] Console.WriteLine("----------------------------------");[/COLOR][/I] [I][COLOR=#5900b3] [/COLOR][/I] [I][COLOR=#5900b3] printString ps1 = new printString(WriteToScreen);[/COLOR][/I] [I][COLOR=#5900b3] printString ps2 = new printString(WriteToFile);[/COLOR][/I] [I][COLOR=#5900b3] sendString(ps1);[/COLOR][/I] [I][COLOR=#5900b3] sendString(ps2);[/COLOR][/I] [I][COLOR=#5900b3] Console.ReadKey();[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3] }[/COLOR][/I] [I][COLOR=#5900b3]}[/COLOR][/I] [COLOR=rgb(0, 0, 0)]Biên dịch và chạy chương trình C# trên sẽ cho kết quả sau:[/COLOR] [/SIZE] [CENTER][SIZE=5][IMG]https://vietjack.com/csharp/images/delegate-2.PNG[/IMG][/SIZE][/CENTER] [SIZE=5][/SIZE] [CENTER][SIZE=5][/SIZE][/CENTER] [SIZE=5]Mặc dù bạn có thể cho rằng delegate không cần thiết và tránh sử dụng nó (một cách trực tiếp) nhưng cuối cùng bạn vẫn phải nhận thấy rằng: mình không thể “sống” khi thiếu delegate. Delegate không khó hiểu cũng như không khó để áp dụng, nếu bạn dành một chút thời gian nghiên cứu. Chúc các bạn thành công! [/SIZE] [RIGHT][SIZE=5][COLOR=#000000]Nguồn: vietjack.com[/COLOR][/SIZE][/RIGHT] [/QUOTE]
Tên
Mã xác nhận
Gửi trả lời
CÔNG NGHỆ
Công Nghệ Thông Tin
Code
Tìm hiểu về Delegate trong C#
Top