1C#如何定义和使用多维数组
不建议使用ArrayList,当数组里的元素是值类型在操作的时候会出现大量的装箱与拆箱步骤性能会损失许多,而是应该用什么类型的元素创建什么类型的数组,除非你的元素有交叉或不确定才考虑采用ArrayList。
多维数组定义如下:
数组可以具有多个维度。例如,下列声明创建一个四行两列的二维数组:
C#
int[,]array = new int[4, 2];
另外,下列声明创建一个三维(4、2 和 3)数组:
C#
int[,,] array1 = new int[4, 2, 3];
数组初始化
可以在声明数组时将其初始化,如下例所示:
C#
int[,]array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
int[, ,] array3D = new int[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } };
也可以初始化数组但不指定级别:
C#
int[,]array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
如果选择声明一个数组变量但不将其初始化,必须使用 new 运算符将一个数组分配给此变量。例如:
C#
int[,]array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // OK
//array5 = {
{1,2}, {3,4}, {5,6}, {7,8}}; // Error
也可以给数组元素赋值,例如:
C#
array5[2,1] = 25;
写一个详细的小例子,用一个动态的STRING型数组存放一个TABLE中的每一个单元中的内容:
DataTabledt = ds.Tables[0];//取出一个内容是动态的表
string[,] str = newstring[dt.Rows.Count,dt.Columns.Count];
//用数组str来存放一个TABLE中的每一个单元中的内容
//dt.Rows.Count是表的行数,dt.Columns.Count是表的例数
for(int i =0;i < dt.Rows.Count ; i++)
{
for(int j=0;j<dt.Columns.Count;j++)
{
str[i,j] =dt.Rows[i][j].ToString().Trim();
}
}
2 定义不定长数组
一维:
int[] numbers = new int[]{1,2,3,4,5,6}; //不定长
int[] numbers = new int[3]{1,2,3};//定长
多维
int[,] numbers = newint[,]{ {1,2,3},{1,2,3}}; //不定长
int[,] numbers = new int[2,2]{ {1,2},{1,2}};//定长
实例:
A:int[] mf1=newint[6];
//注意初始化数组的范围,或者指定初值; //包含6个元素的一维整数数组,初值1,2,3,4,5,6
int[]mf2=new int[6]{1,2,3,4,5,6};
B://一维字符串数组,如果提供了初始值设定项,则还可以省略 new 运算符
string[] mf3={"c","c++","c#"};
C://一维对象数组
Object[] mf4 = new Object[5] { 26, 27, 28, 29, 30 };
D://二维整数数组,初值mf5[0,0]=1,mf5[0,1]=2,mf5[1,0]=3,mf5[1,1]=4
int[,]mf5=new int[,]{ {1,2},{3,4}};
E://6*6的二维整型数组
int[,]mf6=new mf[6,6];
3 实例定义一维和二维数组
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- class