C# delegate Func Action 之间的关系

其实可以把Func、Action都可以理解成是delegate,只是为了方便使用的“语法糖”

delegate的使用

  delegate int Add(int m,int n);
  
  int FAdd(int m,int n){
    return m + n;
  }  

var add  = new Add(FAdd);
add (1,2);

Action的使用 是一种不带返回参数的delegate,而且避免用户进行delegate的定义,直接可以使用

    video sayHello(string name){
      Console.WriteLine($"{name} Hello!");
  }  

Action action = new Action(sayHello);
action("bruce");

Func和Action的区别在于有返回值

    int FAdd(int m,int n){
      Console.WriteLine($"{m + n}");
  return m + n;
  }  

Func func= new Action(FAdd);
Console.WriteLine(func(1,2));

你可能感兴趣的:(C# delegate Func Action 之间的关系)