Lambda匿名函数作为参数

LambdaAnonymous Function as a parameter(Lambda匿名函数作为参数)
本文介绍了Lambda匿名函数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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匿名函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to pass lambda #39;include#39; with multiple levels in Entity Framework Core?(如何在 Entity Framework Core 中传递具有多个级别的 lambda include?)
Join/Where with LINQ and Lambda(使用 LINQ 和 Lambda 加入/在哪里)
Getting all types that implement an interface(获取所有实现接口的类型)
Combining two expressions (Expressionlt;Funclt;T, boolgt;gt;)(组合两个表达式 (ExpressionFuncT, boolgt;))
Is there a reason for C##39;s reuse of the variable in a foreach?(C# 在 foreach 中重用变量是否有原因?)
Lambda/Linq with Contains criteria for multiple keywords(Lambda/LINQ WITH包含多个关键字的条件)