Lambda\Anonymous函数作为参数

Foc*_*ker 14 c# delegates func

我是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; }     );
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用REAL匿名函数(意味着返回结果)?

我不想使用像这样的代表

// Somewhere in a code
{
    Func<int> x = () => { return 0; };

    makeOutput( x())
}
Run Code Online (Sandbox Code Playgroud)

另外我不想改变方法参数类型,如

void makeOutput( Func<int> _param)
{
}
Run Code Online (Sandbox Code Playgroud)

这是非常普遍的决定.


一切正常.我只是明白我想要不可能的东西.我想声明匿名函数并在同一个地方执行它.注意:DIRECT声明和DIRECT调用没有通用包装.

// flash-like (as3) code    /// DOES NOT COMPILE
makeOutput(    (function : int(){ return 0; })()   );
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 29

是.
它被称为代表.

代表是(或多或少)正常类型; 你可以像任何其他类型一样将它们传递给函数.

void makeOutput(Func<int> param) {
    Console.WriteLine(param());
}

makeOutput(delegate { return 4; });
makeOutput(() => { return 4; });
makeOutput(() => 4);
Run Code Online (Sandbox Code Playgroud)

您的编辑问题没有意义.

C#是类型安全的.
如果方法不希望函数作为参数,则不能将方法作为参数赋予它.


Ver*_*cas 5

void makeOutput(Func<int> _param)
{
    makeOutput(_param());
}

void makeOutput(int _param)
{
    Console.WriteLine( _param.ToString());
}
Run Code Online (Sandbox Code Playgroud)

这可以做到这一点!
这是简单的方法:重载!