繁体   English   中英

在if else语句中使用可选的类类型定义变量

[英]define variable with optional class type in if else statement

我需要根据是否设置了参数(opath)来更改类/流类型,但是当我在if-else语句中声明时,netbeans抱怨找不到变量oos。

我不明白这一点,因为var oos总是被设置的,而且它永远都不会被定义?

if(_param.get("opath") != null) {
    FileOutputStream oos = new FileOutputStream(_param.get("opath").toString());
} else {
    OutputStream oos = csocket.getOutputStream();
}

do something with oos...

将您的代码更改为关注

OutputStream oos;    
if(_param.get("opath") != null) {
    oos = new FileOutputStream(_param.get("opath").toString());
} else {
    oos = csocket.getOutputStream();
}
//do something with oos

它只涉及范围,并使对象可用于您要使用它的代码

局部变量的范围受其定义块的限制,在这种情况下为if or else块,因此无法从外部访问它。

您可以将其移出:

OutputStream oos;

if(_param.get("opath") != null) {
    oos = new FileOutputStream(_param.get("opath").toString());
} else {
    oos = csocket.getOutputStream();
}

do something with oos...

使用三元运算符不会遇到此问题,该运算符是“ if-then-else语句的缩写 ”:

OutputStream oos = _param.get("opath") != null ?
  new FileOutputStream(_param.get("opath").toString()) :
  csocket.getOutputStream();

在这种情况下,立即声明并初始化oos

另外,这允许使用常规的if-else语句来定义变量oos甚至final

暂无
暂无

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

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