c# - 没有声明的 Lambda 表达式?

标签 c# lambda expression

来自 MSDN 的 Lambda 表达式示例

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

是否可以在不声明委托(delegate)的情况下做同样的事情?

因为我认为声明不是正确的词,所以我会按照我的意愿编写代码

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


我为什么要这样做?
我想将复杂的 if 条件简化为单个表达式。但我不想膨胀我的类或添加某种辅助类/任何因为它不会在另一个范围内使用。

最佳答案

Is it possible to do the same, without declaring the delegate?

不,不先声明类型就不可能创建 lambda 表达式。委托(delegate)与 C# 中的任何其他对象一样:它必须具有明确定义的类型,然后才能为其赋值。

但是,可能不需要您自己声明类型,因为 Microsoft 已经为您声明了大量类型。如果其中一种预定义的委托(delegate)类型适合您,请随意使用它们。

例如,如果您有一个接受 0 到 16 个参数的委托(delegate),您可以使用 Action 之一委托(delegate)类型:

Action x = () => DoStuff();
Action<int> x = i => DoStuff(i);
Action<string, string, string> = (a,b,c) => DoStuff(a,b,c);

如果需要返回值,可以使用 Func 之一委托(delegate)类型:

Func<int> x = () => 6;
Func<int, int> x = i => i * i;
Func<string, string, string, string> x = (a,b,c) => a.Replace(b, c);

它们还有很多:Windows 窗体或 WPF 中的每个控件事件都使用预定义的委托(delegate)类型,通常是 EventHandlerRoutedEventHandler 或一些派生类型。 Func 有专门的版本,例如 Predicate (尽管那些很大程度上早于 LINQ 并且大多已过时)。

但是,如果出于某种奇怪的原因,没有一种内置委托(delegate)类型适合您,那么是的,您需要先定义自己的委托(delegate)类型,然后才能使用它。

关于c# - 没有声明的 Lambda 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233861/

相关文章:

c# - 所需关键字的正则表达式?

C# 将复选框设置为静态

传递给 create_function 的 PHP 沙箱/清理代码

c# - 在 LINQ-To-SQL 中使用返回表达式的方法

java - Lambda 表达式 java 8 异常 : java. lang.NoSuchMethodError : java. lang.invoke.LambdaMetafactory.metaFactory

c# - Autofac 相当于 StructureMap 的 WhatDoIHave()

c# - 使用 MVVM 模式从 ObservableCollection 添加按钮到 WPF

c# - 循环遍历两个并发字典的 Lambda 表达式

java - 如何使用 Lambda 和 Streams 在 Java 8 中反转单个字符串?

c# - 如何解压表达式树并检查空值