C# 中的委托
csharpprogrammingserver side programming更新于 2024/11/24 6:06:00
C# 中的委托是对方法的引用。委托是保存对方法的引用的引用类型变量。引用可以在运行时更改。
委托特别用于实现事件和回调方法。所有委托都隐式派生自 System.Delegate 类。
让我们看看如何在 C# 中声明委托。
委托 <返回类型> <委托名称> <参数列表>
让我们看一个例子来学习如何在 C# 中使用委托。
示例
using System; using System.IO; namespace DelegateAppl { class PrintString { static FileStream fs; static StreamWriter sw; // 委托声明 public delegate void printString(string s); // 此方法打印到控制台 public static void WriteToScreen(string str) { Console.WriteLine("字符串为: {0}", str); } // 此方法打印到文件 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(); } // 此方法将委托作为参数并使用它来 // 根据需要调用方法 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(); } } }
输出
字符串为:Hello World