C# 委托 Func 、 delegate、Action
参考
- 豆包
- https://blog.csdn.net/baihuomeng2210/article/details/101088283
- https://www.runoob.com/csharp/csharp-delegate.html
- https://learn.microsoft.com/zh-cn/dotnet/api/system.delegate?view=net-9.0#see-also
- https://www.cnblogs.com/liuhaorain/p/3911845.html
- https://blog.csdn.net/m0_65636467/article/details/127804807
- https://learn.microsoft.com/zh-cn/dotnet/api/system.func-1?view=net-9.0
- https://blog.csdn.net/hq0927/article/details/89948780
- https://segmentfault.com/a/1190000011934966
- https://www.cnblogs.com/ybqjymy/p/14281286.html
环境
| 软件/系统 | 版本 | 说明 | 
|---|---|---|
| Windows | windows 10 专业版 22H2 64 位操作系统, 基于 x64 的处理器 | |
| Microsoft Visual Studio | Community 2022 (64 位) - Current 版本 17.13.6 | |
| .NET | 6.0 | 
区别
委托的 Invoke 是同步调用
- delegate: 先声明再使用
- Func:内置委托,无需声明,直接使用,必须有返回值,最后一个泛型参数为返回类型
- Action: 内置委托,无需声明,直接使用,返回类型为 void
代码

- Program.csusing System.Reflection.Metadata; using System.Xml.Linq; namespace ConsoleApp1 { public class Program { static void Main(string[] args) { Console.WriteLine("无参Action"); action = () => Console.WriteLine("无参Action"); action?.Invoke(); Console.WriteLine("有参Action"); action1 = (int parame) => Console.WriteLine("有参Action,参数为:" + parame); action1?.Invoke(123); Console.WriteLine("无参 Func"); func = () => 123; Console.WriteLine(func?.Invoke()); Console.WriteLine("有参 Func,至多14个参数"); func1 = (int parame) => parame + 123; Console.WriteLine(func1?.Invoke(123)); Console.WriteLine("无参 delegate"); Delegate1 delegate1 = Delegate1Method; delegate1?.Invoke(); Console.WriteLine("有参 delegate"); Delegate2 delegate2 = Delegate2Method; delegate2?.Invoke(456); Console.WriteLine("有参 delegate,返回值"); Delegate3 delegate3 = Delegate3Method; int result = delegate3?.Invoke(789) ?? 0; Console.WriteLine("组合 delegate"); Delegate1 delegate4; delegate4 = delegate1; delegate4 += delegate1; delegate4 += delegate1; delegate4 += delegate1; delegate4?.Invoke(); } public static Action action; public static Action<int> action1; public static Func<int>? func; public static Func<int, int>? func1; public delegate void Delegate1(); public delegate void Delegate2(int parame); public delegate int Delegate3(int parame); // static void Delegate1Method() { Console.WriteLine("无参委托"); } static void Delegate2Method(int parame) { Console.WriteLine("有参委托,参数为:" + parame); } static int Delegate3Method(int parame) { Console.WriteLine("有参委托,参数为:" + parame); return parame + 123; } } }
    博  主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/p/18912759
 
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
    
地 址 :https://www.cnblogs.com/xiaqiuchu/p/18912759
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号