简体   繁体   English

在处理间隔时,是否有一种优雅的方法可以用开关之类的东西代替?

[英]Is there an elegant way to replace if by something like switch when dealing with intervals?

Is there a way in .NET to replace a code where intervals are compared like .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
        }

by something more elegant like a switch statement (I think in Javascript "case (<10)" works, but in c#)? 通过更优雅的东西,如switch语句(我认为在Javascript中,“ case(<10)”有效,但在c#中)? Does anyone else find this code is ugly as well? 还有人发现这个代码也很丑吗?

One simplification: since these are all else-if instead of just if , you don't need to check the negation of the previous conditions. 一种简化:因为所有这些都是-if而不是if ,您无需检查先前条件的否定情况。 Ie, this is equivalent to your code: 即,这等效于您的代码:

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

Since you've already affirmed that compare >= 10 after the first if , you really don't need the lower bound test on the second (or any of the other) if s... 由于您已经确定在第一个if之后compare >= 10 ,因此您真的不需要在第二个(或其他任何一个) if上进行下限测试。

It's not pretty, but switch was originally implemented by hashing in C, so that it was actually faster than an if...else if chain. 它不是很漂亮,但是switch最初是由C语言中的哈希实现的,因此它实际上比if...else if链要快。 Such an implementation doesn't translate well to general ranges, and that's also why only constant cases were allowed. 这样的实现不能很好地转换为一般范围,这也是为什么只允许恒定大小写的原因。

However, for the example you give you could actually do something like: 但是,对于您给出的示例,您实际上可以执行以下操作:

switch(compare/10) {
    case 0:
        // Do one thing
    break;
    case 1:
        // Do another thing
    break;
    case 2:
        // Do yet another thing
    break;
    default;
        // Do nothing
    break;
}

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

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