在C#中,“=>”的含义是什么?

3

可能是重复问题:
C# Lambda ( => )

例如

Messenger.Default.Register<AboutToCloseMessage>(this, (msg) =>
        {
            if (msg.TheContainer == this.MyContainer) // only care if my container.
            {
                // decide whether or not we should cancel the Close
                if (!(this.MyContainer.CanIClose))
                {
                    msg.Execute(true); // indicate Cancel status via msg callback.
                }
            }
        });

10
可以展示一下如何搜索 => 符号吗? - BoltClock
6
如果Rdeluca知道“=>”表示“lambda表达式”,他就不会一开始就提问了。 - BoltClock
1
是啊..我不知道它叫lambda,否则我就会搜索了。谢谢! - Rdeluca
5个回答

2

1

这是一个lambda表达式,它允许你轻松地创建一个函数。

在你的例子中,你也可以写成:

Messenger.Default.Register<AboutToCloseMessage>(this, delegate(Message msg)
{
    if (msg.TheContainer == this.MyContainer) // only care if my container.
    {
        // decide whether or not we should cancel the Close
        if (!(this.MyContainer.CanIClose))
        {
            msg.Execute(true); // indicate Cancel status via msg callback.
        }
    }
});

或者甚至更好

Messenger.Default.Register<AboutToCloseMessage>(this, foobar);

// somewhere after //
private void foobar(Message msg)
{
    if (msg.TheContainer == this.MyContainer) // only care if my container.
    {
        // decide whether or not we should cancel the Close
        if (!(this.MyContainer.CanIClose))
        {
            msg.Execute(true); // indicate Cancel status via msg callback.
        }
    }
}

0

这是一个 Lambda 表达式(http://msdn.microsoft.com/en-us/library/bb397687.aspx)。


0

这是一个lambda表达式(函数参数)=> {函数体}

参数的类型可以指定,但编译器通常会自动解释它。


0
这就是在C#中定义lambda的方式。`msg`是传递给lambda方法的参数,其余部分是该方法的主体。
相当于这个的是:
Messenger.Default.Register<AboutToCloseMessage>(this, SomeMethod);

void SomeMethod(SomeType msg)
{
    if (msg.TheContainer == this.MyContainer) // only care if my container.
    {
        // decide whether or not we should cancel the Close
        if (!(this.MyContainer.CanIClose))
        {
             msg.Execute(true); // indicate Cancel status via msg callback.
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接