gpt4 book ai didi

c# - 在处理间隔时,是否有一种优雅的方法可以用 switch 之类的东西替换 if ?

转载 作者:太空狗 更新时间:2023-10-29 23:10:48 25 4
gpt4 key购买 nike

.NET 中有没有一种方法可以替换像这样比较间隔的代码

if (compare < 10)
{
// Do one thing
}
else if (10 <= compare && compare < 20)
{
// Do another thing
}
else if (20 <= compare && compare < 30)
{
// Do yet another thing
}
else
{
// Do nothing
}

通过一些更优雅的东西,比如 switch 语句(我认为在 Javascript 中“case (<10)”有效,但在 c# 中)?还有其他人觉得这段代码也很丑吗?

最佳答案

一个简化:因为这些都是 else-if 而不仅仅是 if,您不需要检查前面条件的否定。即,这等同于您的代码:

if (compare < 10)
{
// Do one thing
}
else if (compare < 20)
{
// Do another thing
}
else if (compare < 30)
{
// Do yet another thing
}
else
{
// Do nothing
}

关于c# - 在处理间隔时,是否有一种优雅的方法可以用 switch 之类的东西替换 if ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5353212/

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