C# 中的委托是什么?
csharpprogrammingserver side programming更新于 2025/9/26 18:37:17
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;
// 委托声明
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();
}
}
}
输出
The String is: Hello World

