ArrayList and Array difference
With reference to MSDN, It is stated that "You can set the lower bound of an Array, but the lower bound of an ArrayList is always zero"
If i declare an array a[10], the lower bound is always a[0]开发者_运维知识库.
Is this the lower bound specified there? If yes, How can we set the lower bound of an array, Since the index of an array always starts with a[0].
Or is the lower bound stated in the link is something different?
Note: I know the link point to the contents of .NET Framework 1.1 but still curious to know what exactly they have mentioned.
You can create an array with a non-zero lowerbound using Array.CreateInstance
.
Note that you won't be able to cast that to a Foo[]
(where Foo
is the relevant type) unless you also make it multidimensional. There are two types of array inside the CLR - a vector (zero based, single dimensional) and an array (can be multi-dimensional and have non-zero lower bound).
A T[]
in C# always corresponds to a vector, whereas a T[][]
corresponds to an array. So you can do:
int[][] rectangle = (int[][]) Array.CreateInstance(typeof(int),
new int[]{2, 2}, // lengths
new int[]{-1, -1}); // lower bounds
but this will fail:
int[] rectangle = (int[]) Array.CreateInstance(typeof(int),
new int[]{2}, // length
new int[]{-1}); // lower bound
Likewise you can't cast it to IEnumerable<int>
or IList<int>
- although you can iterate over it with IEnumerable
just fine.
Personally I would avoid using non-zero lower-bounded arrays like the plague. They're slow, and painful to work with.
The lower bound in C# and VB.NET is always at 0
. Visual Basic 6.0 and older allowed for variable lower bounds. They removed it for the rewriting of the language for .NET.
Here is an article that goes into detail of how to do it: http://msdn.microsoft.com/en-us/magazine/cc301755.aspx. Look for "Creating Arrays with a Non-zero Lower Bound"
精彩评论