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!