Lambda \ Anonymous函数作为参数
我是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; } ); }
是否可以使用REAL匿名函数(意味着返回结果)?
我不想使用像这样的代表
// Somewhere in a code { Func x = () => { return 0; }; makeOutput( x()) }
另外,我不想更改方法参数类型,如
void makeOutput( Func _param) { }
这是非常普遍的决定。
一切正常。 我只是明白我想要不可能的东西。 我想声明匿名函数并在同一个地方执行它。 注意:没有通用包装器的DIRECT声明和DIRECT调用。
// flash-like (as3) code /// DOES NOT COMPILE makeOutput( (function : int(){ return 0; })() );
是。
它被称为代表。
代表是(或多或少)正常类型; 你可以像任何其他类型一样将它们传递给函数。
void makeOutput(Func param) { Console.WriteLine(param()); } makeOutput(delegate { return 4; }); makeOutput(() => { return 4; }); makeOutput(() => 4);
您的编辑问题没有意义。
C#是类型安全的。
如果方法不希望函数作为参数,则不能将方法作为参数赋予它。
void makeOutput(Func _param) { makeOutput(_param()); } void makeOutput(int _param) { Console.WriteLine( _param.ToString()); }
这可以做到这一点!
这是简单的方法:重载!
我有类似的问题,朋友给我指路:
makeOutput((new Func(() => { return 0; })).Invoke());
希望这会有所帮助