Lambda\Anonymous Function as a parameter

前端 未结 3 724
我在风中等你
我在风中等你 2021-01-04 05:44

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

//..         


        
相关标签:
3条回答
  • 2021-01-04 06:28

    I had similar problem and friend showed me the way:

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

    Hope this will help

    0 讨论(0)
  • 2021-01-04 06:35

    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.

    0 讨论(0)
  • 2021-01-04 06:35
    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!

    0 讨论(0)
提交回复
热议问题