【问题标题】:What's the meaning of "=>" in C#? [duplicate]C#中的“=>”是什么意思? [复制]
【发布时间】:2011-06-08 13:16:25
【问题描述】:

可能重复:
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.
                }
            }
        });

【问题讨论】:

  • @Shakti Singh:您能告诉我们如何搜索=&gt; 符号吗?
  • @Shakti Singh:如果 Rdeluca 知道 =&gt; 的意思是“lambda 表达式”,他一开始就不会问了。
  • 是的.. 不知道它被称为 lambda 或者我会搜索它。谢谢!

标签: c# syntax lambda


【解决方案1】:

=>
运算符用于 Lambda 表达式。

http://msdn.microsoft.com/en-us/library/bb397687.aspx

它允许您“即时”定义匿名函数,并可用于创建委托或表达式树类型。

【讨论】:

    【解决方案2】:

    它是一个 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.
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          【解决方案5】:

          这就是您在 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.
                  }
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2019-09-12
            • 2018-06-24
            • 2011-03-29
            • 1970-01-01
            • 2019-12-08
            • 2015-06-25
            • 1970-01-01
            • 2013-02-12
            相关资源
            最近更新 更多