C#lambda表达式可以返回空吗? [英] Can a C# lambda expression ever return void?

查看:399
本文介绍了C#lambda表达式可以返回空吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下方法,并且我想知道是否可以在下面的default(void)内放置任何内容,因为存在编译器错误,指出void在这里无效:

I have the following method, and I want to know if there is anything that can go in place default(void) below because there is a compiler error that says that void is not valid here:

private void applyDefaultsIfNecessary(ApplicationConfiguration configuration)
{
    var defaults = new Dictionary<Predicate<ApplicationConfiguration>, Action<ApplicationConfiguration>>()
    {
       // { rule, action } - if rule is true, execute action 
       { (c) => c.ConnectionString == null , (c) => c.ConnectionString = "foo" },
       { (c) => c.OutputExcelFilePath == null, (c) => c.ConnectionString = "bar" },
       { (c) => c.OutputDirectory == null, (c) => c.OutputDirectory = "baz" }

    };

    //Nothing to select, but we want to loop throough the dict and invoke action, if rule is true.
    //It is a pity there is no extension method called DoForEach on collections.
    defaults.Select((item) => item.Key.Invoke(configuration) ? item.Value.Invoke(configuration) : default(void)  );
}

我意识到我可以使用if-else语句代替三元运算符(或者我可以调用虚拟方法以返回void)。另外,Select扩展方法不喜欢返回void的lambda。似乎无法推断出该类型,但是如果我这样指定类型,则当然可以:

I realize that I can use the if-else statement instead of the ternary operator (or that I could call a dummy method to return void). Also, the Select extension method does not like lambdas that return void. It seems to say that the type cannot be inferred, but of course if I specify the type like this, either:

defaults.Select<ApplicationConfiguration, void>((item) => { if (item.Key.Invoke(configuration)) item.Value.Invoke(configuration); } );

从语言设计的角度来看,我很好奇,为什么我们没有可以返回void或

I was curious from a language design standpoint, why we don't have expressions that can return void or the data type for variables that is void.

推荐答案

我请您参考规范的7.1节,其中指出:

I refer you to section 7.1 of the specification, which states:


[表达式可以分类为]
无。当
表达式是返回类型为void的
方法的调用时,会发生这种情况。
被归类为无的表达式仅在
语句表达式的上下文中有效。

[添加了强调]。

也就是说,您唯一可以使用作为返回值的方法调用的表达式的时间是该表达式构成了整个语句。像这样:

M();

这篇关于C#lambda表达式可以返回空吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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