C# 委托三种使用
不带返回值的委托
public delegate void DelegateDemo(String s1, String s2);
public static event DelegateDemo ddo;
public class Test1
{
public void Look1(String s1, String s2)
{
Console.WriteLine("Look1 " + s1 + " -1- " + s2);
}
public void Look2(String s1, String s2)
{
Console.WriteLine("Look2 " + s1 + " -2- " + s2);
}
public void Look3(String s1, String s2)
{
Console.WriteLine("Look3 " + s1 + " -3- " + s2);
}
}
static void Main(string[] args)
{
Test1 test1 = new Test1();
//方式一 不定义事件event
DelegateDemo dd = new DelegateDemo(test1.Look1);
dd += new DelegateDemo(test1.Look2);
dd += new DelegateDemo(test1.Look3);
dd += new DelegateDemo(test1.Look3);
dd += new DelegateDemo(test1.Look3);
dd("111","222");
dd("333","444");
//方法二 先定义好事件event
ddo += new DelegateDemo(test1.Look1);
ddo("555","666");
Console.ReadKey();
}
Look1 111 -1- 222
Look2 111 -2- 222
Look3 111 -3- 222
Look3 111 -3- 222
Look3 111 -3- 222
Look1 333 -1- 444
Look2 333 -2- 444
Look3 333 -3- 444
Look3 333 -3- 444
Look3 333 -3- 444
Look1 555 -1- 666
带参数返回值的阻塞委托
//委托:具有 同样参数和返回值 的函数的集合.
public delegate string MyDelegate(int arg, string str);
public static string MyFunction1(int count, string str)
{
Debug.Print("count: "+count+" str: "+str);
for (int i=0;i<3;i++)
{
Thread.Sleep(1000 * 3);
Debug.Print("---sleep---");
}
return "MyFunction1";
}
private void Load()
{
MyDelegate dele = new MyDelegate(MyFunction1);
IAsyncResult res = dele.BeginInvoke(10, "abcd", null, null);
string result = dele.EndInvoke(res);
Debug.Print("result: "+result);
IAsyncResult res2 = dele.BeginInvoke(20, "efgh", null, null);
string result2 = dele.EndInvoke(res2);
Debug.Print("result2: " + result2);
Debug.Print("END");
}
count: 10 str: abcd
---sleep---
---sleep---
---sleep---
result: MyFunction1
count: 20 str: efgh
---sleep---
---sleep---
---sleep---
result2: MyFunction1
END
//该方法会阻塞在EndInvoke方法
带参数返回值的非阻塞委托
public delegate string MyDelegate(int arg, string str);
public static string MyFunction1(int count, string str)
{
Debug.Print("count: "+count+" str: "+str);
for (int i=0;i<3;i++)
{
Thread.Sleep(1000 * 3);
Debug.Print("---sleep---");
}
return "MyFunction1";
}
private void Load()
{
MyDelegate dele = new MyDelegate(MyFunction1);
dele.BeginInvoke(10, "abcd", CallBackFun, dele);
Debug.Print("END");
}
public void CallBackFun(IAsyncResult ar)
{
MyDelegate caller = ar.AsyncState as MyDelegate;
string result = caller.EndInvoke(ar);
Debug.Print("result: " + result);
Debug.Print("Completed!");
}
count: 10 str: abcd
END
---sleep---
---sleep---
---sleep---
result: MyFunction1
Completed!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南