14

我是 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; }     );
}

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

我不想使用代表,例如

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

    makeOutput( x())
}

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

void makeOutput( Func<int> _param)
{
}

这是非常普遍的决定。


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

// flash-like (as3) code    /// DOES NOT COMPILE
makeOutput(    (function : int(){ return 0; })()   );
4

3 回答 3

29

是的。
它被称为代表。

代表是(或多或少)普通类型;您可以像任何其他类型一样将它们传递给函数。

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

makeOutput(delegate { return 4; });
makeOutput(() => { return 4; });
makeOutput(() => 4);

您的编辑问题没有意义。

C# 是类型安全的。
如果方法不想将函数作为参数,则不能将方法作为参数。

于 2011-07-28T22:07:01.063 回答
5
void makeOutput(Func<int> _param)
{
    makeOutput(_param());
}

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

这可以解决问题!
这是最简单的方法:重载!

于 2011-07-28T22:07:17.957 回答
4

我有类似的问题,朋友给我指路:

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

希望这会有所帮助

于 2013-10-10T10:51:19.370 回答