如何在 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-06-20

218 次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

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