How can I create an ArrayList with a starting index of 1 (instead of 0)

后端 未结 8 637
春和景丽
春和景丽 2021-01-04 09:47

How can I start the index in an ArrayList at 1 instead of 0? Is there a way to do that directly in code?

(Note that I am asking for ArrayList

相关标签:
8条回答
  • 2021-01-04 10:29
    Stuff getValueAtOneBasedIndex(ArrayList<Stuff> list, index) {
         return list.get(index -1);
    }
    
    0 讨论(0)
  • 2021-01-04 10:33

    One legitimate reason to do this is in writing unit tests. Certain 3rd party SDKs (for example Excel COM interop) expect you to work with arrays that have one-based indices. If you're working with such an SDK, you can and should stub out this functionality in your C# test framework.

    The following should work:

    object[,] comInteropArray = Array.CreateInstance(
        typeof(object),
        new int[] { 3, 5 },
        new int[] { 1, 1 }) as object[,];
    
    System.Diagnostics.Debug.Assert(
         1 == comInteropArray.GetLowerBound(0),
        "Does it look like a COM interop array?");
    System.Diagnostics.Debug.Assert(
         1 == comInteropArray.GetLowerBound(1),
        "Does it still look like a COM interop array?");
    

    I don't know if it's possible to cast this as a standard C# style array. Probably not. I also don't know of clean way to hard-code the initial values of such an array, other than looping to copy them from a standard C# array with hard-coded initial values. Neither of these shortcomings should be a big deal in test code.

    0 讨论(0)
提交回复
热议问题