C#:匿名方法

前一阵子去面试,面试题中看到诸多这种写法:

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.
*/


综上,使用匿名方法,几年下来,可以帮我们少敲很多代码,不是么偷笑



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值