gpt4 book ai didi

Java:If 构造中的初始化条件(性能)

转载 作者:行者123 更新时间:2023-12-01 07:58:20 27 4
gpt4 key购买 nike

我正在寻找在 if 条件中启动变量的可能性,因此它仅在条件范围内有效。

示例:我想改变这个:

String tmp;
if ((tmp = functionWithALotOfProcessingTime()) != null)
{
// tmp is valid in this scope
// do something with tmp
}
// tmp is valid here too

类似这样的事情:

if ((String tmp = functionWithALotOfProcessingTime()) != null)
{
// tmp is *ONLY* in this scope valid
// do something with tmp
}

最佳答案

我可以想到两种方法:

  • 您需要一个额外的作用域,{...}try{...}catch... 并声明 tmp 在该范围内。

  • 将您的 if 逻辑包装在私有(private)方法中,并在方法中声明 tmp,这样在您的主逻辑中,就无法访​​问 tmp

关于Java:If 构造中的初始化条件(性能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27355790/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com