【问题标题】:What is a more concise way of calculating the offset?计算偏移量的更简洁的方法是什么?
【发布时间】:2012-10-11 19:01:03
【问题描述】:

这段代码:

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]。

【问题讨论】:

  • 摆脱colBases,一切都好
  • 你试过什么?你有没有尝试过你的任何一个想法?这似乎不是一个经过充分研究的问题。
  • columnBase * 4 + 1 打动了我……当然,如果它对你来说已经足够了。

标签: c# arrays algorithm refactoring


【解决方案1】:

怎么样:

private int GetColumnToPopulate(int columnBase, int offset) {
   return (columnBase * 4) + 1 + offset;
}

【讨论】:

    【解决方案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];
    

    【讨论】:

      【解决方案3】:

      在我看来你应该用这个表达式替换开关 duckbillColNum = columnBase*4 +1; 不是吗?

      【讨论】:

        【解决方案4】:

        这只是一个简单的数学模式:

        private int GetColumnToPopulate(int columnBase, int offset) 
        { return 1 + (columnBase * 4) + offset; }
        

        【讨论】:

          猜你喜欢
          • 2013-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多