void方法中的Return语句 [英] Return statement in void method

查看:94
本文介绍了void方法中的Return语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下返回空值的方法,我需要在另一个也返回空值的方法中使用它.我可以执行以下操作吗?

I have the following method that returns void and I need to use it in another method that also returns void. Can I do the following?

public void doSomething(){}

public void myMethod()
{
    return doSomething();
}

感谢您的所有评论,但让我更具体一点

Thanks for all your comments, but let me be more specific

如果有事情发生,我只会 doSomething ,否则我会做其他事情

I only doSomething if something happens, otherwise I do other things

public void doSomething(){}

public void myMethod()
{
    for(...)
        if(somethingHappens)
        {
            doSomething();
            return;
        }

    doOtherStuff();
}

代替上面的代码,我可以只在if语句中编写 return doSomething(); 吗?

Instead of the code above, can I just write return doSomething(); inside the if statement?

推荐答案

不,只需执行以下操作:

No, just do this:

public void doSomething() { }

public void myMethod()
{
    doSomething();
}

或在第二种情况下:

public void doSomething() { }

public void myMethod()
{
    // ...
    if (somethingHappens)
    {
        doSomething();
        return;
    }
    // ...
}

返回无效"表示什么也不返回.如果您想跳出" myMethod 的正文,请使用 return; .编译器不允许编写 return void; (表达式的非法开头")或 return doSomething(); (无法从结果类型为void的方法中返回值").我了解返回方法调用的无效"或无效结果"似乎合乎逻辑,但是这样的代码会产生误导.我的意思是,大多数阅读诸如 return doSomething(); 之类的程序的程序员都会认为有某事要返回.

"Returning void" means returning nothing. If you would like to "jump" out of myMethod's body, use return; The compiler does not allow writing return void; ("illegal start of expression") or return doSomething(); ("cannot return a value from method whose result type is void"). I understand it seems logical to return "void" or the "void result" of a method call, but such a code would be misleading. I mean most programmers who read something like return doSomething(); would think there is something to return.

这篇关于void方法中的Return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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