翻译匿名函数
Translate anonymous function
如果你有带有这种类型参数的函数 Func<bool,bool>
我知道这可以是一个具有一个 bool
和 returns 一个 bool
类型参数的函数也是。
我看到人们在这里传递 lambda 是这样的:(x => x)
,这是什么意思?怎么翻译成普通函数?
可以类比这个常规方法:
public bool SomeMethod(bool x)
{
return x;
}
实际上它返回提供给 lambda 表达式的同一个变量。
如果您查看 lambda 表达式 MSDN 文档,它说:
the lambda expression x => x * x specifies a parameter that’s named x
and returns the value of x squared. You can assign this expression to
a delegate type.
要将其转换为普通函数,您可以将其编写为:
public bool MethodName(bool x)
{
return x;
}
Func<bool,bool>
| |
input |
output
相当于
public bool Foo(bool bar)
{
return bar; // do something with bar
}
你也可以有很多输入参数,例如
Func<bool, bool, bool>
| | |
input1 input2 |
output
相当于
public bool Foo(bool foo, bool bar)
{
return foo && bar; // do something with foo and bar
}
如果您的输出只是 void
,您可以使用 Action<T>
Action<bool, bool, bool>
| | |
input1 input2 input3
相当于
public void Foo(bool foo, bool bar, bool foobar)
{
this.result = foo && bar && foobar; // do something with foo and bar and foobar
// ouch! no return because it's a void
}
如果你有带有这种类型参数的函数 Func<bool,bool>
我知道这可以是一个具有一个 bool
和 returns 一个 bool
类型参数的函数也是。
我看到人们在这里传递 lambda 是这样的:(x => x)
,这是什么意思?怎么翻译成普通函数?
可以类比这个常规方法:
public bool SomeMethod(bool x)
{
return x;
}
实际上它返回提供给 lambda 表达式的同一个变量。
如果您查看 lambda 表达式 MSDN 文档,它说:
the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type.
要将其转换为普通函数,您可以将其编写为:
public bool MethodName(bool x)
{
return x;
}
Func<bool,bool>
| |
input |
output
相当于
public bool Foo(bool bar)
{
return bar; // do something with bar
}
你也可以有很多输入参数,例如
Func<bool, bool, bool>
| | |
input1 input2 |
output
相当于
public bool Foo(bool foo, bool bar)
{
return foo && bar; // do something with foo and bar
}
如果您的输出只是 void
,您可以使用 Action<T>
Action<bool, bool, bool>
| | |
input1 input2 input3
相当于
public void Foo(bool foo, bool bar, bool foobar)
{
this.result = foo && bar && foobar; // do something with foo and bar and foobar
// ouch! no return because it's a void
}