我是 C# 的新手。只是玩弄它。并非出于真正目的。
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; } );
}
是否可以使用真正的匿名函数(意味着返回结果)?
我不想使用这样的委托(delegate)
// Somewhere in a code
{
Func<int> x = () => { return 0; };
makeOutput( x())
}
我也不想更改方法参数类型,例如
void makeOutput( Func<int> _param)
{
}
这是很常见的决定。
一切正常。我只是明白我想要不可能的事情。我想声明匿名函数并在同一个地方执行它。注意:没有通用包装器的直接声明和直接调用。
// flash-like (as3) code /// DOES NOT COMPILE
makeOutput( (function : int(){ return 0; })() );
最佳答案
是的。
它称为委托(delegate)。
委托(delegate)是(或多或少)普通类型;您可以像任何其他类型一样将它们传递给函数。
void makeOutput(Func<int> param) {
Console.WriteLine(param());
}
makeOutput(delegate { return 4; });
makeOutput(() => { return 4; });
makeOutput(() => 4);
您的已编辑问题没有意义。
C# 是类型安全的。
如果方法不需要函数作为参数,则不能给它方法作为参数。
关于c# - Lambda\Anonymous 函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6866347/