前一阵子去面试,面试题中看到诸多这种写法:
button1.Click += delegate(System.Object o, System.EventArgs e) { Console.WriteLine("Just test"); };
delegate void Del(int x);
Del d = delegate(int k) { /* ... */ };
虽然知道意思,但是对这种写法比较陌生,遂回来查了一下,原来是C#中的匿名方法。对于它的好处MSDN上是这么说的:
通过使用匿名方法,由于您不必创建单独的方法,因此减少了实例化委托所需的编码系统开销。
什么意思呢?对于上面的两个例子,我们习惯这么写:
public delegate void mydelegate(object obj, EventArgs e);
public static void myclick(object obj, EventArgs e)
{
Console.WriteLine("Just test");
}
mydelegate mm = new mydelegate(myclick);
和
delegate void Del(int x);
public static void myDel(int x)
{
/**/
}
Del dd = new Del(myDel);
其实两种写法的区别就在于:委托绑定的是匿名方法,还是命名方法。
相比之下,绑定匿名方法可以使我们少敲一些代码,这个确实不错。注意匿名方法的delegate前没有new关键字,经常容易写成:
delegate void Del(int x);
Del dd=new delegate(int x){/**/}
是不对的。
附上MSDN的示例:
在线程中使用匿名方法:
void StartThread()
{
System.Threading.Thread t1 = new System.Threading.Thread
(delegate()
{
System.Console.Write("Hello, ");
System.Console.WriteLine("World!");
});
t1.Start();
}
委托绑定
匿名方法后,然后再绑定
命名方法:
delegate void Printer(string s);
class TestClass
{
static void Main()
{
// Instantiate 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.
*/
综上,使用匿名方法,几年下来,可以帮我们少敲很多代码,不是么