来自 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)类型,通常是 EventHandler
或 RoutedEventHandler
或一些派生类型。 Func
有专门的版本,例如 Predicate
(尽管那些很大程度上早于 LINQ 并且大多已过时)。
但是,如果出于某种奇怪的原因,没有一种内置委托(delegate)类型适合您,那么是的,您需要先定义自己的委托(delegate)类型,然后才能使用它。
关于c# - 没有声明的 Lambda 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233861/