msdn 上的说法
匿名方法是指声明委托的一种方法,
在framework 2.0 前,声明委托只有一种方法-命名方法
理解为 委托的参数是个方法名称,且委托和该方法具有相同的签名(参数类型和修饰符)
在framework2.0,引入了匿名方法,如下实例
// Create a handler for a click event button1.Click += delegate(System.Object o, System.EventArgs e) { System.Windows.Forms.MessageBox.Show("Click!"); };
下面例子演示了匿名和命名方法
// Declare a delegate delegate void Printer(string s); class TestClass { static void Main() { // Instatiate the delegate type using an anonymous method: Printer p = delegate(string j) { System.Console.WriteLine(j); }; // Results from the anonymous delegate call: p("The delegate using the anonymous method is called."); // The delegate instantiation using a named method "DoWork": p = new Printer(TestClass.DoWork); // Results from the old style delegate call: p("The delegate using the named method is called."); } // The method associated with the named delegate: static void DoWork(string k) { System.Console.WriteLine(k); } } /* Output: The delegate using the anonymous method is called. The delegate using the named method is called. */ 在framework 3.0及更高版本中,lambda表达式取代了匿名方法。成为为内联代码的首选
lambda的表达方式为
(input parameters)=>expression
其中,是有一个参数的时候括号是可选的,两个或两个以上参数是括号是必须的,且参数之间用逗号隔开。
以下是几个实例:
(x,y)=>x==y
(string x,int y)=>x.length>y
()=>somemethod()
lambda语句为
(input parameters)=>{statement;}
delegate void testdelegate(string s)
...
testdelegate del=n=》{string s=n+",world.";Console.writeline(s);}
转载于:https://blog.51cto.com/mrxiao/194192