C# delegate event func action 匿名方法 lambda表达式

delegate event action func 匿名方法 lambda表达式

  delegate类似c++的函数指针,但是是类型安全的,可以指向多个函数,

  public delegate void DelegateMethod();  //声明了一个Delegate Type
  public DelegateMethod delegateMethod; //声明了一个Delegate对象
  var test = new TestDelegate();

  test.delegateMethod = new TestDelegate.DelegateMethod(test.NonStaticMethod);
   test.delegateMethod += new TestDelegate.DelegateMethod(TestDelegate.StaticMethod);

event用来修饰delegate,不加event的委托就是一个普通的委托,可以直接通过委托调用,加了event的委托是一个事件,只能通过类的成员函数调用。
 action是没有返回值的委托,Action 表示无参,无返回值的委托, Action<int,string> 表示有传入参数int,string无返回值的委托。
func指有返回值的泛型委托,Func<int> 表示无参,返回值为int的委托,Func<object,string,int> 表示传入参数为object, string 返回值为int的委托
 predicate 是返回bool型的泛型委托
匿名方法,不需要使用特定的方法,简化代码,
  1. host.Opened += delegate(object sender, EventArgs e)   
  2. {   
  3.     Console.WriteLine("Service Opened.");   
  4. };   

  不带参数和返回值的匿名方法,可以被具有任何形式签名的委托所指代,如果有一个重载的方法,参数为两种类型的委托,调用这个方法时如果使用不带参数和返回值的匿名方法会编译错误

  1.  static void Output(IntDelegate id)   
  2.     {   
  3.     }   
  4.   
  5.     static void Output(StringDelegate sd)   
  6.     {   
  7.     }   
  8.   
  9.     static void Main(string[] args)   
  10.     {   
  11.        Output(delegate { });   
  12.     }   
lambda表达式也是一种匿名方法,(参数列表)=>表达式或语句块,在编写Lambda表达式时,可以忽略参数的类型,因为编译器能够根据上下文直接推断参数的类型,
  1. (x, y) => x * y         //多参数,隐式类型=> 表达式  
  2. x => x * 5              //单参数, 隐式类型=>表达式  
  3. x => { return x * 5; }      //单参数,隐式类型=>语句块  
  4. (int x) => x * 5            //单参数,显式类型=>表达式  
  5. (int x) => { return x * 5; }      //单参数,显式类型=>语句块  
  6. () => Console.WriteLine()   //无参数 
原文地址:https://www.cnblogs.com/litmin/p/7249375.html