zoukankan      html  css  js  c++  java
  • Nonzerobased Array & Jagged Array in .NET

    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

  • 相关阅读:
    读书笔记7
    读书笔记5
    读书笔记6
    读书笔记4
    读书笔记2
    读书笔记3
    读书笔记1
    嵌入式linux的调试技术
    硬件抽象层:HAL
    蜂鸣器驱动
  • 原文地址:https://www.cnblogs.com/Dah/p/576710.html
Copyright © 2011-2022 走看看