如何最小化此开关?

时间:2019-02-02 11:09:05

标签: c# switch-statement

switch(number){
case 2:
    a+=b;
    break;
case 3:
    a+=b;
    break;
case 4:
    a+=b;
    d=f;
    break;
case 5:
    d=e;
    break;
}

如何最大程度地减少前三种情况下的工作情况?

3 个答案:

答案 0 :(得分:3)

Stopwatch Timer = new Stopwatch();
        for (int i = 0; i < 300; i++) {
            gazeButtonControl[i] = GazeInput.GetGazeElement(GazeBlock[i]);
            gazeButtonControl[i] = new GazeElement();
            GazeInput.SetGazeElement(GazeBlock[i], gazeButtonControl[i]);
            TimeSpan Word[i] = TimeSpan.Zero;
            gazeButtonControl[i].StateChanged += GazeBlockControl[i]_StateChanged;
            void GazeBlockControl[i]_StateChanged(object sender, StateChangedEventArgs ea)
            {
                if (ea.PointerState == PointerState.Enter)
                {
                    Timer.Start();

                }


                if (ea.PointerState == PointerState.Exit)
                {
                    Timer.Stop();
                    Woord[i] += Timer.Elapsed;
                    File.WriteAllText(@"*insert path here", Word[i].ToString());
                    Timer.Reset();
                }
            }
        }

答案 1 :(得分:2)

如果您使用的是C#7,则可以使用模式匹配,即使Jon Skeet正确指出这是一个过大的杀伤力。但是,以防万一,您希望坚持切换大小写并减少“大小写”,您可以执行以下操作

 switch(number)
   {
    case var _ when number == 2 || number==3 || number==4:
        a+=b;
        if(number ==4)
        d=f
     break;
    case 5:
        d=e;
        break;
    }

您也可以用类似的变体替换第一种情况

case var _ when new[]{2,3,4}.Contains(number):

case var _ when number >= 2 || number <= 3: // As pointed by earlier answer

没有模式匹配,您也可以执行以下操作

switch(number)
{
case 2:
case 3:
case 4:
    a+=b;
    if(number ==4)
        d=f;
    break;
case 5:
    d = e;
    break;
}

顺便说一句,如果您的问题是“ a + b”是大约60行代码,那么您始终可以选择使其成为一个函数(并将其移出开关盒)以提高其可读性。

switch(number)
{
case 2:
case 3:
case 4:
    MethodAbAction();
    if(number ==4)
        MethodDFAction();
    break;
case 5:
    MethodDEAction();
    break;
}

顺便说一句,60行的方法从来都不是一件有趣的事。如果可以分拆会更好。

答案 2 :(得分:-1)

if (number != 5)
{
    a += b;
}

if (number == 4)
{
    d = f;
}
else
if (number == 5)
{
    d = e;
}