委托基础
1.什么是委托?
委托是一种定义方法签名的类型,可以与具有兼容签名的任何方法关联。
2.委托有什么特点?
委托类似于 C++ 函数指针,但它们是类型安全的。
委托允许将方法作为参数进行传递。
委托可用于定义回调方法。
委托可以链接在一起;例如,可以对一个事件调用多个方法。
方法不必与委托签名完全匹配。
C# 2.0 版引入了匿名方法的概念,此类方法允许将代码块作为参数传递,以代替单独定义的方法。
C# 3.0 引入了 Lambda 表达式,利用它们可以更简练地编写内联代码块。匿名方法和 Lambda 表达式(在某些上下文中)都可编译为委托类型。这些功能统称为匿名函数。
3.如何使用委托?
Demo:
using System;
namespace ConsoleApplication28
{
class Program
{
public static void FunctionA(string strMessage)
{
Console.WriteLine(strMessage);
}
public delegate void DelegateMethod(string strMessage);
static void Main(string[] args)
{
DelegateMethod handler = FunctionA;
handler("Hello Kevin");
}
}
}
4.匿名方法
在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法,通过使用匿名方法,由于您不必创建单独的方法,因此减少了实例化委托所需的编码系统开销。以下是两个使用匿名方法的示例:
Demo1:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show("The box is click");
};
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}Demo2:
void StartThread()
{
Thread t1 = new Thread
(delegate()
{
MessageBox.Show("Hello,");
MessageBox.Show("Kevin");
});
t1.Start();
}
5.合并委托(多路广播委托)
Demo:
using System;
namespace ConsoleApplication29
{
delegate void DelegageMethod();
class Program
{
static void A()
{
Console.WriteLine("A");
}
static void B()
{
Console.WriteLine("B");
}
static void Main(string[] args)
{
DelegageMethod a, b, c, d;
a = A;
b = B;
c = a + b;
d = c - a;
Console.WriteLine("Invoking delegate a:");
a();
Console.WriteLine("Invoking delegate b:");
b();
Console.WriteLine("Invoking delegate c:");
c();
Console.WriteLine("Invoking delegate d:");
d();
}
}
}
输出结果:
Invoking delegate a:
A
Invoking delegate b:
B
Invoking delegate c:
A
B
Invoking delegate d:
B
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本