什么是 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.