将匿名表达式编写为lambda表达式

时间:2019-01-06 16:16:30

标签: c# lambda delegates console-application anonymous-methods

如何在“ Lambda表达式”中编写相同的“匿名表达式”。

namespace AnonymouseAndLambdaExpression
{
    // Delegate
    public delegate bool NumberHandler(int number);

    class Program
    {
        static void Main(string[] args)
        {
            //..
            NumberHandler _NumberHandler = delegate (int Number) { return Number == 100; };

            bool result = _NumberHandler(100);
            Console.WriteLine("Result : {0}" , result);
        }
    }
}

我们将不胜感激。

1 个答案:

答案 0 :(得分:3)

因为NumberHandler接受类型为int一个参数并返回一个bool,它就是:

NumberHandler _numberHandler = (int number) => number == 100;

或:

NumberHandler _numberHandler = number => number == 100;

此外,我会避免重新发明轮子,而是使用Predicate<int>,即

Predicate<int> _numberHandler = number => number == 100;

我也强烈建议您阅读Lambda Expressions (C# Programming Guide)