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

218 个浏览量

开启您的 职业生涯

通过完成课程并获得认证

立即开始
广告
© . All rights reserved.