Why is it not allowed to declare empty expression body for methods?

时间:2017-04-10 00:33:38

标签: c# resharper c#-7.0

I had a method which has an empty body like this:

public void Foo()
{
}

As suggested by ReSharper I wanted to convert it to expression body to save some space and it became:

public void Foo() => ;

Which doesn't compile. Is there a specific reason why this is not supported ?

And I think I should open a bug ticket for ReSharper since it refactors code to a non-compilable version.

3 个答案:

答案 0 :(得分:15)

As you can see, expression body uses the lambda operator ("=>"). If you still want to write your empty void method as an expression body, you can use Expression.Empty() to show that Foo() is an empty (void) expression.

Methods that return void or Task should be implemented with expressions that don’t return anything, either. (https://msdn.microsoft.com/en-us/magazine/dn802602.aspx)

The following code piece should work.

public void Foo() => Expression.Empty();

Also I agree with your last comment that it is a Resharper bug.

答案 1 :(得分:0)

来自docs

表达式主体定义具有以下常规语法:

member =>表达式;

其中表达式是有效表达式

也:

表示表达式的方法由单个表达式组成,该表达式 返回值,其类型与方法的返回类型相符 返回void且执行某些操作的方法。

因此,如果您想使用表情强壮的成员,则实际上确实需要... 表达式(惊奇!)

但是您仍然可以使用常规样式:

string Property
{
    get => _value;
    set { } // empty
}

void Method() { } // empty

答案 2 :(得分:-1)

new object() 更好。

Expression.Empty() 真的没有任何意义。