Lambda\\Anonymous Function as a parameter

半世苍凉 提交于 2019-11-30 11:35:49
SLaks

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.

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!

I had similar problem and friend showed me the way:

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

Hope this will help

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