此代码:
private int GetColumnToPopulate(int columnBase, int offset) {
int duckbillColNum = 0;
switch (columnBase) {
case 0:
duckbillColNum = 1;
break;
case 1:
duckbillColNum = 5;
break;
case 2:
duckbillColNum = 9;
break;
case 3:
duckbillColNum = 13;
break;
case 4:
duckbillColNum = 17;
break;
case 5:
duckbillColNum = 21;
break;
case 6:
duckbillColNum = 25;
break;
case 7:
duckbillColNum = 29;
break;
}
duckbillColNum += offset;
return duckbillColNum;
}
......很容易理解,但是冗长而笨重。我想精简它。我的伪代码想法是这样的:
int[] colBases
{
0..7
}
int[] offsets
{
1,5,9,13,17,21,25,29
}
int idx = colBases.IndexOf(columnBase);
duckbillColNum = offsets[idx];
...或者也许是一个多维的int数组?无论如何,“IndexOf”业务当然不会[ile,ute]。
答案 0 :(得分:5)
怎么样:
private int GetColumnToPopulate(int columnBase, int offset) {
return (columnBase * 4) + 1 + offset;
}
答案 1 :(得分:2)
考虑使用Dictionary
,你可以这样定义:
Dictionary<int, int> offsets = new Dictionary<int, int>()
{
{ 0, 1 },
{ 1, 5 },
{ 2, 9 },
{ 3, 13 },
{ 4, 17 },
{ 5, 21 },
{ 6, 25 },
{ 7, 29 },
}
然后使用它时:
return offsets[columnBase];
答案 2 :(得分:1)
在我看来,你应该用这个表达式替换开关duckbillColNum = columnBase*4 +1;
不是吗?
答案 3 :(得分:1)
这只是一个简单的数学模式:
private int GetColumnToPopulate(int columnBase, int offset)
{ return 1 + (columnBase * 4) + offset; }