Initializing an array on arbitrary starting index

2019-01-12 07:09发布

问题:

Is it possible in c# to initialize an array in, for example, subindex 1?

I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes.

As a workaround I am cloning the original array, modifying that one, and setting it as a whole when I'm done.

But, I was wondering if it was possible to create a new non-zero based array

回答1:

You can use Array.CreateInstance.

See Array Types in .NET



回答2:

It is possible to do as you request see the code below.

// Construct an array containing ints that has a length of 10 and a lower bound of 1
Array lowerBoundArray = Array.CreateInstance(typeof(int), new int[1] { 10 }, new int[1] { 1 });

// insert 1 into position 1
lowerBoundArray.SetValue(1, 1);

//insert 2 into position 2
lowerBoundArray.SetValue(2, 2);

// IndexOutOfRangeException the lower bound of the array 
// is 1 and we are attempting to write into 0
lowerBoundArray.SetValue(1, 0);


回答3:

Not simply. But you can certainly write your own class. It would have an array as a private variable, and the user would think his array starts at 1, but really it starts at zero and you're subtracting 1 from all of his array accesses.



回答4:

You can write your own array class



回答5:

I don't think if it's possible to modify the starting index of arrays.

I would create my own array using generics and handle it inside.



回答6:

Just keep of const int named 'offset' with a value of one, and always add that to your subscripts in your code.



回答7:

I don't think you can create non-zero based arrays in C#, but you could easily write a wrapper class of your own around the built in data structures.This wrapper class would hold a private instance of the array type you required; overloading the [] indexing operator is not allowed, but you can add an indexer to a class to make it behave like an indexable array, see here. The index function you write could then add (or subtract) 1, to all index's passed in.

You could then use your object as follows, and it would behave correctly:

myArrayObject[1]; //would return the zeroth element.


回答8:

In VB6 you could change the array to start with 0 or 1, so I think VBScript can do the same. For C#, it's not possible but you can simply add NULL value in the first [0] and start real value at [1]. Of course, this is a little dangerous...