System.Console.Write("{0}", jaggedArray4[0][1, 0]);
方法 Length 返回包含在交错数组中的数组的数目。例如,假定您已声明了前一个数组,则此行:
System.Console.WriteLine(jaggedArray4.Length);
返回值 3。
本例生成一个数组,该数组的元素为数组自身。每一个数组元素都有不同的大小。
class ArrayTest
{
static void Main()
{
// Declare the array of two elements:
int[][] arr = new int[2][];
// Initialize the elements:
arr[0] = new int[5] { 1, 3, 5, 7, 9 };
arr[1] = new int[4] { 2, 4, 6, 8 };
// Display the array elements:
for (int i = 0; i < arr.Length; i++)
{
System.Console.Write("Element({0}): ", i);
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");
}
System.Console.WriteLine();
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
输出:
Element(0): 1 3 5 7 9
Element(1): 2 4 6 8
隐式类型的数组
可以创建隐式类型的数组,在这样的数组中,数组实例的类型是从数组初始值设定项中指定的元素推断而来的。有关任何隐式类型变量的规则也适用于隐式类型的数组。
在查询表达式中,隐式类型的数组通常与匿名类型以及对象初始值设定项和集合初始值设定项一起使用。
下面的示例演示如何创建隐式类型的数组:
class ImplicitlyTypedArraySample
{
static void Main()
{
var a = new[] { 1, 10, 100, 1000 }; // int[]
var b = new[] { "hello", null, "world" }; // string[]
// single-dimension jagged array
var c = new[]
{
new[]{1,2,3,4},
new[]{5,6,7,8}
};
// jagged array of strings
var d = new[]
{
new[]{"Luca", "Mads", "Luke", "Dinesh"},
new[]{"Karen", "Suma", "Frances"}
};
}
}
请注意,在上一个示例中,没有在初始化语句的左侧对隐式类型的数组使用方括号。另请注意,交错数组就像一维数组那样使用 new [] 进行初始化。
对象初始值设定项中的隐式类型的数组
创建包含数组的匿名类型时,必须在该类型的对象初始值设定项中对数组进行隐式类型化。在下面的示例中,contacts 是一个隐式类型的匿名类型数组,其中每个匿名类型都包含一个名为 PhoneNumbers 的数组。请注意,对象初始值设定项内部未使用 var 关键字。










