C#中的多播委托和泛型委托
更新時間:2022年05月04日 16:25:59 作者:農(nóng)碼一生
這篇文章介紹了C#中的多播委托和泛型委托,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
多播委托
簡介
- 每一個委托都是繼承自MulticastDelegate,也就是每個都是多播委托。
- 帶返回值的多播委托只返回最后一個方法的值
- 多播委托可以用加減號來操作方法的增加或者減少。
- 給委托傳遞相同方法時 生成的委托實例也是相同的(也就是同一個委托)
代碼實現(xiàn)
//聲明委托
delegate void MulticastTest();
public class MulticastDelegateTest
{
public void Show()
{
MulticastTest multicastTest = new MulticastTest(MethodTest);
multicastTest();
Action action =new Action(MethodTest);
action = (Action)MulticastDelegate.Combine(action, new Action(MethodTest2));
action = (Action)MulticastDelegate.Combine(action, new Action(MethodTest3));
action = (Action)MulticastDelegate.Remove(action, new Action(MethodTest3));
action();
//等同于上面
action = MethodTest;
action += MethodTest2;
action += MethodTest3;
action -= MethodTest3;
foreach (Action action1 in action.GetInvocationList())
{
action1();
}
Console.WriteLine("==========");
action();
Func<string> func = () => { return "我是Lambda"; };
func += () => { return "我是func1"; };
func += () => { return "我是func2"; };
func += GetTest;
func += GetTest; //給委托傳遞相同方法時 生成的委托實例也是相同的(也就是同一個委托)
string result = func();
Console.WriteLine(result);
Console.WriteLine("==========");
}
#region 委托方法
public void MethodTest()
{
Console.WriteLine("我是方法MethodTest()1");
}
public void MethodTest2()
{
Console.WriteLine("我是方法MethodTest()2");
}
public void MethodTest3()
{
Console.WriteLine("我是方法MethodTest()3");
}
public string GetTest()
{
return "我是方法GetTest()";
}
#endregion
}泛型委托
代碼實現(xiàn)
//泛型委托聲明
delegate void GenericDelegate<T>(T t);
public class GenericDelegate
{
public static void InvokeDelegate()
{
GenericDelegate<string> genericDelegate = new GenericDelegate<string>(Method1);
genericDelegate("我是泛型委托1");
//官方版本(不帶返回值)
Action<string> action = new Action<string>(Method1);
action("我是泛型委托1");
//Action<string, string, string, string, string, string, string, string, string, string, string, string, string, string, string, string>
GenericDelegate<int> genericDelegate1 = new GenericDelegate<int>(Method2);
genericDelegate1(2);
//官方版本(帶回值)
Func<string, string> func = new Func<string, string>(Method3);
string ret = func("我是帶返回值Func委托");
Console.WriteLine( ret );
//Func<string, string, string, string, string, string, string, string, string, string, string, string, string, string, string, string,string>
}
#region 委托方法
public static void Method1(string str)
{
Console.WriteLine(str);
}
public static void Method2(int num)
{
Console.WriteLine("我是泛型委托2 "+num);
}
public static string Method3(string str )
{
return str;
}
#endregion
}以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
C#實現(xiàn)微信公眾號群發(fā)消息(解決一天只能發(fā)一次的限制)實例分享
經(jīng)過幾天研究網(wǎng)上的代碼和謝燦大神的幫忙,今天終于用C#實現(xiàn)了微信公眾號群發(fā)消息,現(xiàn)在分享一下2013-09-09
深入多線程之:內(nèi)存柵欄與volatile關(guān)鍵字的使用分析
本篇文章對內(nèi)存柵欄與volatile關(guān)鍵字的使用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

