将 lambda 表达式用于事件处理程序 [英] Using lambda expressions for event handlers

查看:37
本文介绍了将 lambda 表达式用于事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个声明如下的页面:

I currently have a page which is declared as follows:

public partial class MyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //snip
        MyButton.Click += (o, i) =>
        {
            //snip
        }
    }
}

我最近才从 1.1 迁移到 .NET 3.5,所以我习惯于在 Page_Load 之外编写事件处理程序.我的问题是;在为此使用 lambda 方法时,我应该注意任何性能缺陷或陷阱吗?我更喜欢它,因为它肯定更简洁,但我不想牺牲性能来使用它.谢谢.

I've only recently moved to .NET 3.5 from 1.1, so I'm used to writing event handlers outside of the Page_Load. My question is; are there any performance drawbacks or pitfalls I should watch out for when using the lambda method for this? I prefer it, as it's certainly more concise, but I do not want to sacrifice performance to use it. Thanks.

推荐答案

没有性能影响,因为编译器会将您的 lambda 表达式转换为等效的委托.Lambda 表达式只不过是一种语言功能,编译器会将其翻译为您习惯使用的完全相同的代码.

There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.

编译器会将您拥有的代码转换成这样:

The compiler will convert the code you have to something like this:

public partial class MyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //snip
        MyButton.Click += new EventHandler(delegate (Object o, EventArgs a) 
        {
            //snip
        });
    }
}

这篇关于将 lambda 表达式用于事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆