c# - Lambda\Anonymous 函数作为参数

标签 c# delegates func

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

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

我不想使用这样的委托(delegate)

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

最佳答案

是的。
它称为委托(delegate)。

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

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

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

您的已编辑问题没有意义。

C# 是类型安全的。
如果方法不需要函数作为参数,则不能给它方法作为参数。

关于c# - Lambda\Anonymous 函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6866347/

相关文章:

ios - 使用委托(delegate)将值保存到核心数据

ios - 通过触摸按钮显示广告横幅

variables - 如何通过包共享变量

c# - Owin 授权超时后 EF 抛出 AspNetUsers 错误

c# - 对超过 UInt16 屏障的程序集信息进行版本控制

c# - 非静态类中私有(private)静态变量的范围

c# - 简单的 C# 事件参数问题

c# - 在 C# 中使用 setter 作为参数? (也许有委托(delegate)?)

c# - 添加代表 : unexpected results when adding two Func<T, TResult>

c# - C# 中 VB ReadOnly 属性的等价物是什么?