委托之Action和Func

本文介紹了C#中的Action和Func委託的使用方法,通過具體示例展示了如何將委託應用於計算操作中。Action委託用於沒有返回值的方法,而Func委託則用於有返回值的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//Action 和 Func是C#類庫準備好的兩個委託,直接拿來用即可
namespace Action和Func委託
{
	class Program
	{
		static void Main( string[] args )
		{
			Calculate calculator = new Calculate();// 有這個實例之後才可以調用它的方法
			//Action 這個委託指向了Report方法,
			Action action = new Action( calculator.Report );
			// 直接調用
			calculator.Report();
			//兩種間接調用方法,
			action.Invoke();
			action();
			// Func 委託
			Func<int, int, int> func1 = new Func<int, int, int>( calculator.Add );
			Func<int, int, int> func2 = new Func<int, int, int>( calculator.Sub);
			int x = 100;
			int y = 200;
			int z;
			z = func1.Invoke( x, y );
			Console.WriteLine( z );
			z = func2.Invoke( x, y );
			Console.WriteLine(z);
			Console.Read();
		}
	}
	class Calculate
	{// Class Caculate has Three methods
		public void Report()//first method Report,參數列表為空,無返回值
		{
			Console.WriteLine("I have 3 Methods");
		}
		public int Add( int a, int b )
		{
			int Res = a + b;
			return Res;
		}
		public int Sub( int a, int b )
		{
			int Res = a - b;
			return Res;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值