在void方法结束时返回意味着什么? [英] What does return mean at the end of a void method?

查看:238
本文介绍了在void方法结束时返回意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 void 方法不会返回任何值,但我仍然可以编写类似

I know that a void method does not return any value, but I can still write code like

void nothingDohere() {return;}

那么,怎么样? void在这里使用return语句?

So, How can "void" work with the "return" statement here?

推荐答案

没有值的return语句只能 用于 void 方法(或构造函数),并简单地执行退出现在的方法部分返回。可以认为带有返回值的语句有两个目的:

A return statement without a value can only be used in a void method (or a constructor), and simply performs the "get out of the method now" part of returning. Think of a return-with-value statement has having two purposes:


  • 终止执行当前方法(通过最后块当然)

  • 使用调用者可用的方法计算一个值

  • Terminating execution of the current method (via finally blocks of course)
  • Making a value computed in the method available to the caller

void 方法中的return语句只能实现其中的第一个;第二个在 void 方法中没有任何意义。

The return statement in a void method simply achieves the first of these; the second makes no sense in a void method.

来自第14.17节


没有表达式的return语句必须包含在声明的方法体中,使用关键字void,不返回任何值(§8.4),或者在构造函数体中(§8.8) 。如果返回语句出现在实例初始化程序或静态初始化程序(第7.7节)中,则会发生编译时错误。没有Expression的return语句尝试将控制权转移给包含它的方法或构造函数的调用者。
确切地说,没有表达式的return语句总是突然完成,原因是没有值的返回。

A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (§8.4), or in the body of a constructor (§8.8). A compile-time error occurs if a return statement appears within an instance initializer or a static initializer (§8.7). A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it. To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value.

这篇关于在void方法结束时返回意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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