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;
}
}
}
委托之Action和Func
最新推荐文章于 2024-07-13 16:26:45 发布