参考:C#语言入门详解https://www.bilibili.com/video/BV1wx411K7rb?p=19 刘猛铁
留言区评论笔记https://www.yuque.com/yuejiangliu/dotnet/timothy-csharp-019
C#语言中的委托是函数指针的升级版。
Action 和 Func 是 C# 内置的委托实例,它们都有很多重载以方便使用。
using System;
namespace DelegateExample
{
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
Action action = new Action(calculator.Report); // 委托
calculator.Report();
action.Invoke();
action();
Func<int, int, int> func1 = new Func<int, int, int>(calculator.Add); // 泛型委托
Func<int, int, int> func2 = new Func<int, int, int>(calculator.Sub);
Console.WriteLine(func1(4, 5));
Console.WriteLine(func2(4, 5));
}
}
class Calculator
{
public void Report()
{
Console.WriteLine("I have three methods.");
}
public int Add(int a,int b)
{
return a + b;
}
public int Sub(int a,int b)
{
return a - b;
}
}
}
自定义委托
委托是类,所以声明位置是和 class 处于同一个级别。但 C# 允许嵌套声明类(一个类里面可以声明另一个类),所以有时也会有 delegate 在 class 内部声明的情况。
using System;
namespace DelegateExample
{
public delegate double fun(double a, double b);
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
fun fun1 = new fun(calculator.Add);
Console.WriteLine(fun1(7,6));
}
}
class Calculator
{
public void Report()
{
Console.WriteLine("I have three methods.");
}
public double Add(double a, double b)
{
return a + b;
}
public double Sub(double a, double b)
{
return a - b;
}
public double Mul(double a,double b)
{
return a * b;
}
public double Div(double a,double b)
{
return a / b;
}
}
}
委托作为属性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Calculator calculator = new Calculator();
Action action1 = new Action(calculator.Report);
action1.Invoke();
calculator.ReportAction = new Action<string>(calculator.ReportName);
calculator.ReportAction("Pocky");
calculator.AddFunc = new Func<int, int, int>(calculator.Add);
Console.WriteLine(calculator.AddFunc(1, 2));
}
}
class Calculator
{
public void Report()
{
Console.WriteLine("Come on!");
}
public void ReportName(string name)
{
Console.WriteLine("My name is ");
Console.WriteLine(name);
}
public int Add(int a,int b)
{
return a + b;
}
public void Report2(string a)
{
if(ReportAction == null)
{
return;
}
this.ReportAction(a);
}
public Action<string> ReportAction { get; set; }
public Func<int,int,int> AddFunc { get; set; }
}
}