可以在C#中的前pression以往任何时候都返回void?以往、时候、pression、void

2023-09-03 17:27:27 作者:愛你ぺ愛过了头

我有以下的方法,和我想知道是否有任何可以去的地方默认(无效)以下,因为有一个编译器错误,指出作废无效在这里:

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)。此外,选择扩展方法不喜欢返回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); } );

我是从语言设计的角度来看,为什么我们没有EX pressions可以返回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:

[一名前pression可以被分类为]   一无所有。这发生在   EX pression是一个调用   方法为void返回类型。    Nothing类别的前pression只是在一个范围内有效   声明EX pression。

[An expression may be classified as] "nothing". This occurs when the expression is an invocation of a method with a return type of void. An expression classified as nothing is only valid in the context of a statement expression.

[强调]。

这是说,您可以使用EX pression这是一个void返回方法调用的时候,前pression构成了一个完整的语句的唯一一次。像这样的:

That is to say that the only time you may use an expression which is a void-returning method invocation is when the expression makes up an entire statement. Like this:

M();