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

后端 未结 8 741
春和景丽
春和景丽 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:12

    Here is something I am using right now to quickly port a VBA application to C#:

    It's an Array class that starts with 1 and accepts multiple dimensions.

    Although there is some additional work to do (IEnumerator, etc...), it's a start, and is enough to me as I only use indexers.

    public class OneBasedArray
    {
        Array innerArray;
    
        public OneBasedArray(params int[] lengths)
        {
            innerArray = Array.CreateInstance(typeof(T), lengths, Enumerable.Repeat(1, lengths.Length).ToArray());
        }
    
        public T this[params int[] i]
        {
            get
            {
                return (T)innerArray.GetValue(i);
            }
            set
            {
                innerArray.SetValue(value, i);
            }
        }
    }
    

提交回复
热议问题