写一个lambda或匿名函数,它接受一个out参数 [英] Write a lambda or anonymous function that accepts an out parameter

查看:634
本文介绍了写一个lambda或匿名函数,它接受一个out参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在code定义一个委托:

I have a delegate defined in my code:

public bool delegate CutoffDateDelegate( out DateTime cutoffDate );

我想创建委托并初始化一个lambda或匿名函数,但这些都不编译。

I would like to create delegate and initialize with a lambda or anonymous function, but neither of these compiled.

CutoffDateDelegate del1 = dt => { dt = DateTime.Now; return true; }
CutoffDateDelegate del2 = delegate( out dt ) { dt = DateTime.Now; return true; }

有没有办法做到这一点?

Is there way to do this?

推荐答案

您可以使用的lambda或匿名委托语法 - 你只需要指定参数的类型,并将其标记为出来:

public delegate bool CutoffDateDelegate( out DateTime cutoffDate );

// using lambda syntax:
CutoffDateDelegate d1 = 
    (out DateTime dt) => { dt = DateTime.Now; return true; };

// using anonymous delegate syntax:
CutoffDateDelegate d2 = 
    delegate( out DateTime dt ) { dt = DateTime.Now; return true; }

虽然明确宣称的参数作为参考输入/输出的预期,不必声明参数类型的Lambda EX pression是不常见的,因为编译器通常可以推断出它们。在这种情况下,然而,编译器目前不用于推断在lambda /匿名EX pressions out或ref参数的类型。我不能肯定,如果这种行为是错误/监督,或者如果有一个语言之所以必须如此,但有一个很容易的解决方法。

While explicitly declaring arguments as ref/out is expected, having to declare argument types in lambda expression is less common since the compiler can normally infer them. In this case, however, the compiler does not currently infer the types for out or ref arguments in lambda/anon expressions. I'm not certain if this behavior is a bug/oversight or if there's a language reason why this must be so, but there's an easy enough workaround.

编辑:我做了一个快速检查在VS2010β2,它仍然看起来像你必须定义的参数类型 - 它们不是推断C#4

I did a quick check in VS2010 β2, and it still looks like you have to define the argument types - they are not inferred for C# 4.

这篇关于写一个lambda或匿名函数,它接受一个out参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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