C# 委托 Func 、 delegate、Action

参考

环境

软件/系统 版本 说明
Windows windows 10 专业版 22H2 64 位操作系统, 基于 x64 的处理器
Microsoft Visual Studio Community 2022 (64 位) - Current 版本 17.13.6
.NET 6.0

区别

委托的 Invoke 是同步调用

  • delegate: 先声明再使用
  • Func:内置委托,无需声明,直接使用,必须有返回值,最后一个泛型参数为返回类型
  • Action: 内置委托,无需声明,直接使用,返回类型为 void

代码

image

  1. Program.cs
    using 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;
    		}
    
    
    
    	}
    }
    
    
    
posted @ 2025-06-05 17:21  夏秋初  阅读(19)  评论(0)    收藏  举报