使很长的 switch 语句更具可读性

我写了一个 switch 语句,里面有超过 11 种情况,如下所示......


switch (x)

{

    case x = 0:

        x = x + 1;

    break;

    case x = 1:

        x = x + 2;

    break;

    // and so one...

}

问题是我发现以这种方式编写代码看起来很丑陋并且难以维护,是否有另一种格式化方式使其更具可读性?


郎朗坤
浏览 159回答 1
1回答

拉莫斯之舞

您当前的代码无法编译,我认为您的意思是:switch (x){&nbsp; &nbsp; case 0:&nbsp; &nbsp; &nbsp; &nbsp; x = x + 1;&nbsp; &nbsp; break;&nbsp; &nbsp; case 1:&nbsp; &nbsp; &nbsp; &nbsp; x = x + 2;&nbsp; &nbsp; break;}这只是我自己的疯狂猜测,但 switch 语句的其余部分可能如下所示:case 2:&nbsp; &nbsp; x = x + 3;break;case 3:&nbsp; &nbsp; x = x + 4;break;case 4:&nbsp; &nbsp; x = x + 5;break;您可以将整个事情简化为:x += x + 1如果我猜错了,您仍然可以尝试使用字典来简化它。下面是一个例子:// It could also be a Dictionary<int, Func<int, int>> or some other delegate// if you want to compute the value from "x" or execute some random codeDictionary<int, int> xDict = new Dictionary<int, int> {&nbsp; &nbsp; {0, <some value you want x to be>},&nbsp; &nbsp; {1, <some value you want x to be>},&nbsp; &nbsp; //...}x = xDict[x];
打开App,查看更多内容
随时随地看视频慕课网APP