<!DOCTYPE html>
    <html lang="vi" xmlns="http://www.w3.org/1999/xhtml" prefix="og: http://ogp.me/ns#">
    <head>
<title>Delegate trong C&#x23;</title>
<meta name="description" content="Delegate trong C&#x23; - Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;www.nguoicodonvn2008.info&#x002F;vi&#x002F;news&#x002F;savefile&#x002F;kien-thuc-may-tinh&#x002F;delegate-trong-c-6685.html">
<meta name="author" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :.">
<meta name="copyright" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :. [admin@nguoicodonvn2008.info]">
<meta name="robots" content="index, archive, follow, noodp">
<meta name="googlebot" content="index,archive,follow,noodp">
<meta name="msnbot" content="all,index,follow">
<meta name="generator" content="NukeViet v4.5">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta property="og:title" content="Delegate trong C&#x23;">
<meta property="og:type" content="website">
<meta property="og:description" content="Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;www.nguoicodonvn2008.info&#x002F;vi&#x002F;news&#x002F;savefile&#x002F;kien-thuc-may-tinh&#x002F;delegate-trong-c-6685.html">
<meta property="og:site_name" content=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.">
<meta property="og:url" content="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/delegate-trong-c-6685.html">
<link rel="shortcut icon" href="https://www.nguoicodonvn2008.info/favicon.ico">
<link rel="canonical" href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/delegate-trong-c-6685.html">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/" title="Tin Tức" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/karaoke-dual/" title="Tin Tức - Karaoke Dual" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/nhac-tre/" title="Tin Tức - Nhạc trẻ" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tru-tinh/" title="Tin Tức - Trữ tình" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/nuoc-ngoai/" title="Tin Tức - Nước ngoài" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/remix/" title="Tin Tức - Remix" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tam-su-tinh-yeu/" title="Tin Tức - Tâm sự tình yêu" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tho-suu-tam/" title="Tin Tức - Thơ sưu tầm" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/cuoc-song/" title="Tin Tức - Cuộc sống" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/phan-mem/" title="Tin Tức - Phần mềm" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/kien-thuc-may-tinh/" title="Tin Tức - Kiến thức máy tính" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/hoc-tap/" title="Tin Tức - Học tập" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tai-lieu/" title="Tin Tức - Tài liệu" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/de-thi/" title="Tin Tức - Đề thi" type="application/rss+xml">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/assets/css/font-awesome.min.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/style.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/style.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/news.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/custom.css" type="text/css">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/jquery/jquery.min.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/language/vi.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/global.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/site.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/news.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/main.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/custom.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/bootstrap.min.js" type="text/javascript">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/style.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/style.non-responsive.css">
<link rel="StyleSheet" href="https://www.nguoicodonvn2008.info/themes/default/css/news.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/custom.css">
<style type="text/css">
	body{background: #fff;}
</style>
    </head>
    <body>
<div id="print">
	<div id="hd_print">
		<h2 class="pull-left">.&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.</h2>
		<p class="pull-right"><a title=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;." href="https://www.nguoicodonvn2008.info/">https://www.nguoicodonvn2008.info</a></p>
	</div>
	<div class="clear"></div>
	<hr />
	<div id="content">
		<h1>Delegate trong C&#x23;</h1>
		<ul class="list-inline">
			<li>Thứ hai - 06/02/2023 23:47</li>
			<li class="hidden-print txtrequired"><em class="fa fa-print">&nbsp;</em><a title="In ra" href="javascript:;" onclick="window.print()">In ra</a></li>
			<li class="hidden-print txtrequired"><em class="fa fa-power-off">&nbsp;</em><a title="Đóng cửa sổ này" href="javascript:;" onclick="window.close()">Đóng cửa sổ này</a></li>
		</ul>
		<div class="clear"></div>
		<div id="hometext">
		</div>
				<div class="imghome">
			<img alt="Delegate trong C&#x23;" src="https://st.quantrimang.com/photos/image/2018/07/24/chuoi-string-trong-c-200-size-80x80-znd.jpg" width="460" class="img-thumbnail" />
		</div>
		<div class="clear"></div>
		<div id="bodytext" class="clearfix">
			<p style="text-align: justify;"><strong>Delegate trong C#</strong>&nbsp;là gì? Nếu chưa biết câu trả lời, mời bạn tham khảo những điều cần biết về&nbsp;<strong>Delegate trong C#</strong>.</p>

<p style="text-align: justify;">Delegate trong&nbsp;<a href="https://quantrimang.com/hoc/csharp" title="Ngôn ngữ lập trình C# ">C#</a>&nbsp;là tương tự như con trỏ tới các hàm, trong C hoặc trong C++.&nbsp;<strong>Delegate</strong>&nbsp;là một biến kiểu tham chiếu chứa tham chiếu tới một phương thức. Tham chiếu đó có thể được thay đổi tại runtime.</p>

<p style="text-align: justify;">Đặc biệt, các delegate đượ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 dẫn xuất ngầm từ lớp&nbsp;<strong>System.Delegate</strong>&nbsp;trong C#.</p>

<h2 style="text-align: justify;">Khai báo Delegate trong C#</h2>

<p style="text-align: justify;">Khai báo Delegate trong C# xác định các phương thức có thể được Delegate tham chiếu. 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 đó.</p>

<p style="text-align: justify;">Ví dụ, xét delegate sau:</p>

<pre id="pre0" style="text-align: justify;">
public delegate int MyDelegate (string s);</pre>

<p style="text-align: justify;">Delegate trên có thể được sử dụng để tham chiếu bất kỳ phương thức nào có một tham số string đơn và trả về một biến kiểu&nbsp;<em>int</em>.</p>

<p style="text-align: justify;">Cú pháp để khai báo delegate trong C# là:</p>

<pre id="pre1" style="text-align: justify;">
delegate &lt;kiểu_trả_về&gt; &lt;tên_delegate&gt; &lt;danh_sách_tham_số&gt;</pre>

<h2 style="text-align: justify;">Khởi tạo Delegate trong C#</h2>

<p style="text-align: justify;">Khi kiểu delegate được khai báo, đối tượng delegate phải được tạo với từ khóa&nbsp;<strong>new</strong>&nbsp;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ụ:</p>

<pre id="pre2" style="text-align: justify;">
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);</pre>

<p style="text-align: justify;">Ví dụ sau minh họa cách khai báo, khởi tạo và sử dụng delegate để tham chiếu các phương thức, lấy tham số nguyên (integer) và trả về một giá trị integer.</p>

<pre id="pre3" style="text-align: justify;">
using System;

delegate int NumberChanger(int n);
namespace DelegateAppl {
   class TestDelegate {
      static int num = 10;
      public static int AddNum(int p) {
         num += p;
         return num;
      }
      public static int MultNum(int q) {
         num *= q;
         return num;
      }
      public static int getNum() {
         return num;
      }
      static void Main(string&#91;&#93; args) {
         //tạo thể hiện delegate
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         //gọi phương thức sử dụng đối tượng delegate
         nc1(25);
         Console.WriteLine(&quot;Giá trị của số: {0}&quot;, getNum());
         nc2(5);
         Console.WriteLine(&quot;Giá trị của số: {0}&quot;, getNum());
         Console.ReadKey();
      }
   }
}</pre>

<p style="text-align: justify;">Khi chạy code trên bạn sẽ nhận được kết quả như sau:</p>

<pre id="pre4" style="text-align: justify;">
Giá trị của số: 35
Giá trị của số: 175</pre>

<h2 style="text-align: justify;">Multicast (đa hướng) một Delegate trong C#</h2>

<p style="text-align: justify;">Các đối tượng Delegate có thể được hợp thành từ các delegate khác nhờ toán tử &quot;+&quot;. 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 mới có thể được hợp thành. Toán tử &quot;-&quot; có thể được sử dụng để gỡ bỏ một delegate thành phần khỏi một delegate được hợp thành.</p>

<p style="text-align: justify;">Sử dụng đặ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à&nbsp;<strong>Multicasting</strong>&nbsp;của một Delegate. Chương trình ví dụ sau minh họa Multicasting của một Delegate trong C#:</p>

<pre id="pre5" style="text-align: justify;">
using System;

delegate int NumberChanger(int n);
namespace QTMCSharp {
   class Tester {
      static int num = 10;
      public static int AddNum(int p) {
         num += p;
         return num;
      }
      public static int MultNum(int q) {
         num *= q;
         return num;
      }
      public static int getNum() {
         return num;
      }
      static void Main(string&#91;&#93; args) {
         //tạo các thể hiện delegate 
         NumberChanger nc;
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         nc = nc1;
         nc += nc2;
         //gọi multicast
         nc(5);
         Console.WriteLine(&quot;Giá trị của số: {0}&quot;, getNum());
         Console.ReadKey();
      }
   }
}</pre>

<p style="text-align: justify;">Kết quả khi chạy chương trình trên sẽ như sau:</p>

<pre id="pre6" style="text-align: justify;">
Giá trị của số: 75</pre>

<h2 style="text-align: justify;">Cách sử dụng Delegate trong C#</h2>

<p style="text-align: justify;">Ví dụ dưới đây sẽ minh họa cách sử dụng của delegate trong C#. Delegate với tên printString có thể được sử dụng để tham chiếu phương thức nhận input là một string và không trả về cái gì.</p>

<p style="text-align: justify;">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.</p>

<pre id="pre7" style="text-align: justify;">
using System;
using System.IO;
namespace QTMCsharp {
    class TestCsharp {
        static FileStream fs;
        static StreamWriter sw;

        // khai báo delegate
        public delegate void printString(string s);

        // phương thức thứ nhất để in trên console
        public static void WriteToScreen(string str) {
            Console.WriteLine(&quot;Chuỗi la: {0}&quot;, str);
        }

        //phương thức thứ hai để ghi dữ liệu vào file
        public static void WriteToFile(string s)
        {
            fs = new FileStream(&quot;c:\\message.txt&quot;,
            FileMode.Append, FileAccess.Write);
            sw = new StreamWriter(fs);
            sw.WriteLine(s);
            sw.Flush();
            sw.Close();
            fs.Close();
        }

        // phương thức này nhận delegate làm tham số và
        // sử dụng nó để gọi các phương thức nếu cần.
        public static void sendString(printString ps)
        {
            ps(&quot;Quantrimang.com&quot;);
        }
        static void Main(string&#91;&#93; args)
        {
            Console.WriteLine(&quot;Ví dụ về Delegate C#:&quot;);
            Console.WriteLine(&quot;--------------------------&quot;);
            printString ps1 = new printString(WriteToScreen);
            printString ps2 = new printString(WriteToFile);
            sendString(ps1);
            sendString(ps2);
            Console.ReadKey();
        }
    }
}</pre>

<p style="text-align: justify;">Biên dịch và chạy chương trình C# trên để xem kết quả.</p>

<pre id="pre8" style="text-align: justify;">
Ví dụ về Delegate C#:
--------------------------
Chuỗi là: Quantrimang.com
</pre>

<h2 style="text-align: justify;">Ưu và nhược điểm khi dùng delegate trong C#</h2>

<p style="text-align: justify;"><strong>Ưu điểm:</strong></p>

<ul>
	<li style="text-align: justify;">Giúp gọi các phương thức tĩnh và động.</li>
	<li style="text-align: justify;">Gọi một hoặc nhiều phương thức có cùng đặc điểm</li>
	<li style="text-align: justify;">Xác định phương thức callback và gọi trình xử lý sự kiện.</li>
	<li style="text-align: justify;">Có thể được kết hợp thành delegate đa hướng để chạy một chuỗi delegate theo thứ tự.</li>
</ul>

<p style="text-align: justify;"><strong>Nhược điểm:</strong></p>

<ul>
	<li style="text-align: justify;">Một delegate sẽ chạy chậm hơn một phương thức thông thường bởi thời gian chạy cần giải quyết tham chiếu phương thức trước khi gọi delegate được xử lý và gọi thành công phương thức.</li>
	<li style="text-align: justify;">Ngoại lệ trong phương thức được tham chiếu bởi một delgate không hiện nguyên nhân gây lỗi. Điều này khiến việc gỡ lỗi trở nên khó khăn hơn.</li>
	<li style="text-align: justify;">Càng sử dụng nhiều delegate, code càng khó đọc.</li>
	<li style="text-align: justify;">Khi dùng delegate, trình biên dịch JIT và runtime có thể tối ưu hóa kém hơn so với các chức năng thông thường.</li>
</ul>

<p style="text-align: justify;">Nhìn chung, Delegate trong C# là lựa chọn phù hợp để lập trình hướng đối tượng. Chỉ cần nắm được những kiến thức cơ bản kể trên, bạn có thể sử dụng delegate C# dễ dàng.</p>
		</div>
				<div id="author">
						<p>
				<strong>Nguồn tin:</strong>
				Quantrimang.com
			</p>
		</div>
	</div>
	<div id="footer" class="clearfix">
		<div id="url">
			<strong>URL của bản tin này: </strong><a href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/delegate-trong-c-6685.html" title="Delegate trong C&#x23;">https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/delegate-trong-c-6685.html</a>

		</div>
		<div class="clear"></div>
		<div class="copyright">
			&copy; .&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.
		</div>
		<div id="contact">
			<a href="mailto:admin@nguoicodonvn2008.info">admin@nguoicodonvn2008.info</a>
		</div>
	</div>
</div>
        <div id="timeoutsess" class="chromeframe">
            Bạn đã không sử dụng Site, <a onclick="timeoutsesscancel();" href="https://www.nguoicodonvn2008.info/#">Bấm vào đây để duy trì trạng thái đăng nhập</a>. Thời gian chờ: <span id="secField"> 60 </span> giây
        </div>
        <div id="openidResult" class="nv-alert" style="display:none"></div>
        <div id="openidBt" data-result="" data-redirect=""></div>
		</script>
		<div class="car-top">
  <span><img src="https://www.nguoicodonvn2008.info/themes/default/images/car.png" alt=""></span>
</div>
<script src="https://www.nguoicodonvn2008.info/assets/js/jquery/jquery.min.js"></script>
<script>var nv_base_siteurl="/",nv_lang_data="vi",nv_lang_interface="vi",nv_name_variable="nv",nv_fc_variable="op",nv_lang_variable="language",nv_module_name="news",nv_func_name="savefile",nv_is_user=0, nv_my_ofs=-4,nv_my_abbr="EDT",nv_cookie_prefix="nv4c_e856T",nv_check_pass_mstime=1738000,nv_area_admin=0,nv_safemode=0,theme_responsive=0,nv_recaptcha_ver=2,nv_recaptcha_sitekey="",nv_recaptcha_type="image",XSSsanitize=1;</script>
<script src="https://www.nguoicodonvn2008.info/assets/js/language/vi.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/global.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/site.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/news.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/main.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/custom.js"></script>
<script type="application/ld+json">
        {
            "@context": "https://schema.org",
            "@type": "Organization",
            "url": "https://www.nguoicodonvn2008.info",
            "logo": "https://www.nguoicodonvn2008.info/uploads/angel.gif"
        }
        </script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/bootstrap.min.js"></script>
<script type="text/javascript">
var $scrolltop = $('.car-top');
$scrolltop.on('click', function () {
    $('html,body').animate({
        scrollTop: 0
    }, 800);
    $(this).addClass("car-run");
    setTimeout(function(){ $scrolltop.removeClass('car-run');}, 1000);
    return false;
});
$(window).on('scroll', function ()
{ 
    if($(window).scrollTop() >= 200)
    {
        $scrolltop.addClass("show");
        $scrolltop.addClass("car-down");
    }
    else
    {
       $scrolltop.removeClass("show");
       setTimeout(function(){ $scrolltop.removeClass('car-down');}, 300);
    }
});
</script>
</body>
</html>