问题描述
我是 C# 的新手.只是玩弄它.不是为了真正的目的.
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)?
我不想使用诸如
// 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)
{
}
这是很常见的决定.
一切都好.我只是明白我想要不可能的事情.我想声明匿名函数并在同一个地方执行它.注意:直接声明和直接调用没有通用包装器.
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; })() );
推荐答案
是的.
它被称为委托.
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);
<小时>
您的编辑问题没有意义.
C# 是类型安全的.
如果方法不希望函数作为参数,则不能将方法作为参数.
C# is type-safe.
If the method doesn't want a function as a parameter, you cannot give it a method as a parameter.
这篇关于Lambda匿名函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!