【问题标题】:Why doesn't this lambda example from the MSDN site work?为什么 MSDN 网站上的这个 lambda 示例不起作用?
【发布时间】:2009-03-10 14:38:08
【问题描述】:

我必须对以下 lambda 示例做什么才能使其工作?

错误:只有赋值、调用、递增、递减和新对象表达式可以用作语句

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace TestLambda
{
    class Program
    {
        static void Main(string[] args)
        {
            delegate int del(int i);
            del myDelegate = x => x * x;
            int j = myDelegate(5); //j = 25
        }

    }

}

【问题讨论】:

  • JaredPar 已经涵盖了它;但请注意,MSDN 示例有时会被缩写。可以说,省略号在这里会更清楚......

标签: c# lambda


【解决方案1】:

您需要在方法之外声明委托:

class Program
{
    delegate int del(int i);

    static void Main(string[] args)
    {            
        del myDelegate = x => x * x;
        int j = myDelegate(5); //j = 25
    }

}

【讨论】:

    【解决方案2】:

    在 C# 中将类型定义为方法体语句是不合法的。您需要将委托移到方法之外才能编译。例如

        delegate int del(int i);
    
    public static void Main(string[] args) {
    
        del myDelegate = x => x * x;
        int j = myDelegate(5); //j = 25
    }
    

    【讨论】:

    • 或者更好,只使用 Func ;-p
    • @Marc,是的。我认为,如果您可以在程序集级别本质上 typedef 一个 Func,Action,那么当一个简单的 Func,Action 可以做到时,它会大大防止人们创建新的委托类型。跨度>
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2014-06-22
    • 1970-01-01
    相关资源
    最近更新 更多