How to create a 1-Dimensional Array in C# with index starting at 1

前端 未结 4 1333
花落未央
花落未央 2021-01-01 20:59

For multidimensional arrays Array.CreateInstance can be used to create non-zero index based arrays, but if you try that for a 1-dimensional arrays (vectors) as in e.g.:

4条回答
  •  有刺的猬
    2021-01-01 21:36

    You can make a non-zero-based array in C#, but the useage of it is kind-of obnoxious. It is definitly not a simple substitute for a normal (i.e., zero-based single dimentional) array.

            // Create the array.
            Array myArray = Array.CreateInstance(typeof(double), new int[1] { 12 }, new int[1] { 1 });
    
            // Fill the array with random values.
            Random rand = new Random();
            for (int index = myArray.GetLowerBound(0); index <= myArray.GetUpperBound(0); index++)
            {
                myArray.SetValue(rand.NextDouble(), index);
            }
    
            // Display the values.
            for (int index = myArray.GetLowerBound(0); index <= myArray.GetUpperBound(0); index++)
            {
                Console.WriteLine("myArray[{0}] = {1}", index, myArray.GetValue(index));
            }
    

    The GetValue/SetValue syntax that is required for this is uglier than subtracting one from a vector index at each occurance.

    If a value type is stored in the array, then it will be stored in consecutive position just as in a regular array, but the getter and setter will require boxing of the values (unless there is some compiler magic that I am not aware of). And the getter will usually require a cast (just to make it even uglier).

        double myValue = (double)myArray.GetValue(index);
    

    Also note that the correct comparison for GetUpperBound is <=, unlike Length which is compared with <.

提交回复
热议问题