这篇文章介绍了C#中的多播委托和泛型委托,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
多播委托
简介
- 每一个委托都是继承自MulticastDelegate,也就是每个都是多播委托。
- 带返回值的多播委托只返回最后一个方法的值
- 多播委托可以用加减号来操作方法的增加或者减少。
- 给委托传递相同方法时 生成的委托实例也是相同的(也就是同一个委托)
代码实现
//声明委托
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
}
泛型委托
代码实现
//泛型委托声明
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
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:C#中的多播委托和泛型委托


基础教程推荐
猜你喜欢
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中的Linq to JSON操作详解 2023-06-08
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C# 解析XML和反序列化的示例 2023-04-14
- Unity shader实现高斯模糊效果 2023-01-16