简体   繁体   中英

Expression-bodied method: Return nothing

I was updating one of our projects to C# 6.0 when I found a method that was literally doing nothing:

private void SomeMethod()
{
    return;
}

Now I was wondering if there is any possibility to rewrite it as an expression-bodied method as it just contains return .

Try 1:

private void SomeMethod() => return;

Exceptions:

  1. ; expected

  2. Invalid token 'return' in class, struct, or interface member declaration

  3. Invalid expression term 'return'

Try 2:

private void SomeMethod() => ;

Exception:

  1. Invalid expression term ';'

Is there any possibility to achieve this (although this method doesn't really make sense)?

这不是表达式主体,但您可以这样做:

private void SomeMethod() { }

Methods which do nothing still make sense - they just do nothing.

You can lose the return statement:

  private void SomeMethod() { }

Or assign a function to a variable instead:

  private Action SomeMethod = () => { };

If you really want to do expression for body on void function, you can do this:

private void SomeFunction() => Expression.Empty();

This uses Linq and creates an empty expression that has Void type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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