C# 语法练习(7): 数组
2009-02-23 08:16:57 来源:WEB开发网先声明, 赋值时再确定维数:
using System;
class MyClass
{
static void Main()
{
int[] arr;
arr = new int[] { 11, 22, 33 };
foreach (int i in arr) Console.WriteLine(i); // 11/22/33
Console.ReadKey();
}
}
可改变声明时的维数:
using System;
class MyClass
{
static void Main()
{
int[] arr = new int[3];
arr = new int[4] { 11, 22, 33, 44 };
foreach (int i in arr) Console.WriteLine(i); // 11/22/33/44
Console.ReadKey();
}
}
如果用变量做数组维数, 一定要是 const:
using System;
class MyClass
{
static void Main()
{
const int size = 3;
int[] arr = new int[size] { 11, 22, 33};
foreach (int i in arr) Console.WriteLine(i); // 11/22/33
Console.ReadKey();
}
}
二维数组初始化:
using System;
class MyClass
{
static void Main()
{
int[,] arr = { {11,12,13,14}, {21,22,23,24}, {31,32,33,34} };
foreach (int i in arr) Console.WriteLine(i);
Console.ReadKey();
}
}
二维数组赋值:
更多精彩
赞助商链接