gpt4 book ai didi

c# 这个设计是 "Correct"吗?

转载 作者:太空狗 更新时间:2023-10-29 21:19:58 24 4
gpt4 key购买 nike

我目前有以下内容

        if (!RunCommand(LogonAsAServiceCommand))
return;

if (!ServicesRunningOrStart())
return;

if (!ServicesStoppedOrHalt())
return;

if (!BashCommand(CreateRuntimeBashCommand))
return;

if (!ServicesStoppedOrHalt())
return;

if (!BashCommand(BootstrapDataBashCommand))
return;

if (!ServicesRunningOrStart())
return;

这样做会更清洁吗?安全吗?

        if (
(RunCommand(LogonAsAServiceCommand))
&& (ServicesRunningOrStart())
&& (ServicesStoppedOrHalt())
&& (BashCommand(CreateRuntimeBashCommand))
&& (ServicesStoppedOrHalt())
&& (BashCommand(BootstrapDataBashCommand))
&& (ServicesRunningOrStart())
)
{
// code after "return statements" here
}

最佳答案

当我看到第一种方法时,我的第一个想法是,以这种方式编写代码的原因是所涉及的操作可能有副作用。从方法的名称来看,我假设它们是这样的?如果是这样,我肯定会选择第一种方法而不是第二种方法;我认为您的代码的读者看到使用短路 && 表达式有条件地执行副作用时会感到非常困惑。

如果没有副作用,两者都可以;它们都是完全可读的。如果你发现有更多的条件或者条件本身在不同的场景中有所不同,你可以尝试这样的事情:

Func<bool>[] conditions = ...
if(conditions.Any(condn => condn()))
{
...
}

但是,对于您的情况,我真的不会采用这种方法。

关于c# 这个设计是 "Correct"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3942606/

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