Lambda\Anonymous Function as a parameter

时光总嘲笑我的痴心妄想 提交于 2019-12-18 19:03:26

问题


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)?

I do not want to use delegates such as

// 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)
{
}

That is very common decision.


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; })()   );

回答1:


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);

Your edited question does not make sense.

C# is type-safe.
If the method doesn't want a function as a parameter, you cannot give it a method as a parameter.




回答2:


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

void makeOutput(int _param)
{
    Console.WriteLine( _param.ToString());
}

This can do the trick!
It's the simples way : overloading!




回答3:


I had similar problem and friend showed me the way:

makeOutput((new Func<Int32>(() => { return 0; })).Invoke());

Hope this will help



来源:https://stackoverflow.com/questions/6866347/lambda-anonymous-function-as-a-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!