简体   繁体   English

虚空型方法表达式主体成员允许非空类型的表达式*如果使用其他方法*

[英]Void-type method expression-bodied member allows expression of non-void type *if other method*

I'm not sure what to make of this, I was playing with expression-bodied members in C#, and I noticed something odd. 我不确定该怎么做,我在和C#中的表达式强成员一起玩,我发现有些奇怪。

Essentially, if you create a method expression-bodied member which has a void return type, you can still use a non-void return type method as the expression. 本质上,如果您创建的方法表达式主体成员具有空返回类型,则仍可以使用非空返回类型方法作为表达式。

Example: 例:

public void MethodA() { }
public void MethodB() => MethodA();

Works as expected. 可以正常工作。

public string MethodA() { return "MethodA"; }
public void MethodB() => MethodA();

Compiles just fine (I haven't run it to test, but the fact that it compiles confuses me). 编译就很好(我还没有运行它进行测试,但是它编译的事实使我感到困惑)。 This confuses me, as in my head I see: 这使我感到困惑,因为在我的脑海中我看到:

public void MethodB() { return MethodA(); }

Which is obviously invalid, as the return statement actually returns a value, which isn't allowed in a void method. 这显然是无效的,因为return语句实际上返回一个值,这在void方法中是不允许的。

However, what's odd is that the following does not compile: 但是,奇怪的是以下代码无法编译:

public void MethodC() => "MethodC";

And gives the "Only assignment..." error. 并给出“仅分配...”错误。

Why is this happening? 为什么会这样呢? Is this intended, or is it some sort of bug? 这是故意的,还是某种错误? Is there something I'm missing? 有什么我想念的吗? Are expression bodied members allowed to just throw-away the result of the expression if it's another method? 如果表达式身体强壮的成员是另一种方法,是否只允许丢弃表达式的结果?

This confuses me, as in my head I see: 这使我感到困惑,因为在我的脑海中我看到:

 public void MethodB() { return MethodA(); } 

That is not actually correct; 这实际上是不正确的。 The actual syntax generated is this: 生成的实际语法是这样的:

public void MethodB() { MethodA(); }

And that is perfectly fine. 那就很好。 The return value is just ignored. 返回值将被忽略。

The "MethodC" code fragment isn't a method which result can be voided. "MethodC"代码片段不是可以使结果无效的方法。 It is an actual value and that needs to be assigned according to C# syntax. 它是一个实际值,需要根据C#语法进行分配。 The same is true for regular statements: putting "MethodC"; 对于常规语句也是如此:放入"MethodC"; on an empty line fails. 在空行上失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM