在处理间隔时,是否有一种优雅的方式来替换像switch这样的东西?

Ola*_*laf 5 .net c# switch-statement

在.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
        }
Run Code Online (Sandbox Code Playgroud)

通过像switch语句更优雅的东西(我认为在Javascript"case(<10)"中有效,但在c#中)?有没有其他人发现这个代码也很难看?

Rei*_*ica 4

一种简化:由于这些都是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
}
Run Code Online (Sandbox Code Playgroud)