C# 中的委託是什麼?


C# 中的委託是對方法的引用。委託是儲存對方法引用的引用型別變數。此引用可以在執行時更改。

託管用於實現事件和回撥方法。所有委託均暗含派生自 System.Delegate 類。

我們來看看如何用 C# 宣告委託。

delegate <return type> <delegate-name> <parameter list>

我們來看一個示例,瞭解如何在 C# 中處理委託。

示例

 線上演示

using System;
using System.IO;

namespace DelegateAppl {

   class PrintString {
      static FileStream fs;
      static StreamWriter sw;

      // delegate declaration
      public delegate void printString(string s);

      // this method prints to the console
      public static void WriteToScreen(string str) {
         Console.WriteLine("The String is: {0}", str);
      }

      //this method prints to a file
      public static void WriteToFile(string s) {
         fs = new FileStream("c:\message.txt",
         FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }

      // this method takes the delegate as a parameter and uses it to
      // call the methods as required
      public static void sendString(printString ps) {
         ps("Hello World");
      }

      static void Main(string[] args) {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }  
}

輸出

The String is: Hello World

更新於: 2020 年 6 月 20 日

245 次瀏覽

開啟您的職業之旅

完成課程獲取認證

開始學習
廣告
© . All rights reserved.