So everybody knows a common array in .NET is zero-based(its index starts at zero), but in .NET world you can also create a N-based array too!

What's a N-based array? e.g. if a array "arr" is 4-based, you must access the first object of the array by using "arr[4]" instead of the default "arr[0]".

Then how to create an non-zero array? Let's sees an example:

Type t1 = Type.GetType("System.Double[*]");
ConstructorInfo[] ctors = t1.GetConstructors();
foreach (ConstructorInfo ci in ctors)
    Console.WriteLine(ci); // print "Void .ctor(Int32)" and "Void .ctor(Int32, Int32)"

Array a1 = (Array)ctors[0].Invoke(new object[] { 10 });
Console.WriteLine(a1.GetType()); // print "System.Double[]"

Array a2 = (Array)ctors[1].Invoke(new object[] { -5, 10 }); // lowerbound: -5
Console.WriteLine(a2.GetType()); // print "System.Double[*]"

So we know the type "System.Double[*]" has two ConstructorInfo which can initialize two kinds of array, the first is zero-based array, and another is non-zero-based.

------------------------------------------------------------------------

Have you known the jagged array? It's not the same as N-dimensional array, it's exactly an array of arrays, and you should notice this:

Type.GetType("System.Int32[,][]") returns a jagged array, more precisely, a one-dimensional array whose elements are two-dimensional arrays, This is different from the type "int[,][]" declared in C#, which is a two-dimensional array of one-dimensional arrays. The type name grammar used in Type.GetType is more close to how IL describes such array: you can see a3's type as "int32[0...,0...][]" in ildasm.

Type t2 = Type.GetType("System.Int32[,][]");
int[][,] a3 = new int[2][,] { new int[,] { { 1, 2 } }, new int[,] { { 3, 4, 5 }, { 6, 7, 8 } } };
int[,][] a4 = new int[1, 2][] { { new int[] { 1, 2 }, new int[] { 3, 4, 5 } } };
Console.WriteLine(a3.GetType() == t2); // True
Console.WriteLine(a4.GetType() == t2); // False

.locals init (
   [6] int32[0...,0...][] a3, 
   [7] int32[][0...,0...] a4,


 Original post: http://blogs.msdn.com/haibo_luo/archive/2006/11/28/1169887.aspx

Posted on 2006-11-29 18:52  Adrian H.  阅读(363)  评论(0编辑  收藏  举报