我写了一个 switch 语句,里面有超过 11 种情况,如下所示......switch (x){ case x = 0: x = x + 1; break; case x = 1: x = x + 2; break; // and so one...}问题是我发现以这种方式编写代码看起来很丑陋并且难以维护,是否有另一种格式化方式使其更具可读性?
1 回答
拉莫斯之舞
TA贡献1820条经验 获得超10个赞
您当前的代码无法编译,我认为您的意思是:
switch (x)
{
case 0:
x = x + 1;
break;
case 1:
x = x + 2;
break;
}
这只是我自己的疯狂猜测,但 switch 语句的其余部分可能如下所示:
case 2:
x = x + 3;
break;
case 3:
x = x + 4;
break;
case 4:
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 code
Dictionary<int, int> xDict = new Dictionary<int, int> {
{0, <some value you want x to be>},
{1, <some value you want x to be>},
//...
}
x = xDict[x];
- 1 回答
- 0 关注
- 158 浏览
添加回答
举报
0/150
提交
取消