如何在 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.