Lambda\Anonymous函数作为参数 [英] Lambda\Anonymous Function as a parameter

查看:293
本文介绍了Lambda\Anonymous函数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个很新的C#。只是玩弄它。不是一个真正的目的。

 无效makeOutput(INT加上_Param)
{
Console.WriteLine(加上_Param,的ToString());
}

// ...
//某处在代码
{
makeOutput(/ *为例子有些不是C#代码是什么我想* /函数:int(){返回0;});
}

是否有可能使用一个真正的匿名函数(指返回结果)<? / p>

我不希望使用委托,如

  //某处在代码
{
Func键< INT> X =()=> {返回0; };

makeOutput(X())
}



此外,我不要想改变方法的参数类型,如

 无效makeOutput(Func键< INT>加上_Param)
{
}

这是很常见的决定。






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

  //类似Flash(AS3)代码///无法编译
makeOutput((函数:int(){返回0;})());


解决方案

是的。结果
这就是所谓的。委托



委托是(更多或更少)的正常类型;你可以将它们传递给函数就像任何其他类型的

 无效MakeOutput(Func键< INT>参数){
Console.WriteLine(参数());
}

makeOutput(代表{返回4;});
makeOutput(()=> {返回4;});
makeOutput(()=→4);






修改的ED问题是没有意义的。



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)?

I do not want to use delegates such as

// 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)
{
}

That is very common decision.


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);


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.

这篇关于Lambda\Anonymous函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆