class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
/// #Action 用法# (无返回值用Action)
Console.WriteLine("---------Action 用法↓--------------------");
Action action = new Action(calculator.Report);
//直接调用
calculator.Report();
//使用委托间接调用1
action.Invoke();
//使用委托间接调用2
action();
Console.WriteLine("---------Func 用法↓--------------------");
/// #Func 用法#(有返回值用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 = 0;
z = func1(x, y);
Console.WriteLine(z);
z = func2(x, y);
Console.WriteLine(z);
Console.ReadLine();
}
}
class Calculator
{
public void Report()
{
Console.WriteLine("I have 3 methods");
}
public int Add(int a, int b)
{
int result = a + b;
return result;
}
public int Sub(int a, int b)
{
int result = a - b;
return result;
}
}
C# 委托Action 、 Func如何使用
最新推荐文章于 2023-11-09 19:30:12 发布