LambdaAnonymous Function as a parameter(Lambda匿名函数作为参数)
问题描述
我是 C# 的新手.只是玩弄它.不是为了真正的目的.
I'm a very new to C#. Just playing around with it. Not for a real purpose.
void makeOutput( int _param)
{
Console.WriteLine( _param.ToString());
}
//...
// Somewhere in a code
{
makeOutput( /* some not c# code for an example for what do I want */ function : int () { return 0; } );
}
是否可以使用真正的匿名函数(意味着返回结果)?
Is it possible to use a REAL anonymous functions (means returning result)?
我不想使用诸如
// Somewhere in a code
{
Func<int> x = () => { return 0; };
makeOutput( x())
}
我也不想更改方法参数类型,例如
Also I DO NOT want to change method parameter type such as
void makeOutput( Func<int> _param)
{
}
这是很常见的决定.
一切都好.我只是明白我想要不可能的事情.我想声明匿名函数并在同一个地方执行它.注意:直接声明和直接调用没有通用包装器.
Everything is alright. I just understood that I wanted impossible things. I wanted to declare anonymous function and execute it in the same place. Note: DIRECT declaring and DIRECT call without generic wrapper.
// flash-like (as3) code /// DOES NOT COMPILE
makeOutput( (function : int(){ return 0; })() );
推荐答案
是的.
它被称为委托.
Yes.
It's called a delegate.
委托是(或多或少)普通类型;您可以像任何其他类型一样将它们传递给函数.
Delegates are (more-or-less) normal types; you can pass them to functions just like any other type.
void makeOutput(Func<int> param) {
Console.WriteLine(param());
}
makeOutput(delegate { return 4; });
makeOutput(() => { return 4; });
makeOutput(() => 4);
<小时>
您的编辑问题没有意义.
C# 是类型安全的.
如果方法不希望函数作为参数,则不能将方法作为参数.
C# is type-safe.
If the method doesn't want a function as a parameter, you cannot give it a method as a parameter.
这篇关于Lambda匿名函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Lambda匿名函数作为参数


基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01