欢迎来到unity学习、unity培训、unity企业培训教育专区,这里有很多U3D资源、U3D培训视频、U3D教程、U3D常见问题、U3D项目源码,我们致力于打造业内unity3d培训、学习第一品牌。
今天老师为我们讲解了数组,我对数组有了一个初步的了解,下面就讲一讲今天学到的知识。
问:如果要储存一个学生的名字,要怎么做?
答:string a=“张三”;
问:如果要储存一组学生的名字要怎么做?(该组的人员有张三,李四,王五。)
答:string a=“张三”;
string b=“李四”;
string c=“王五”;
问:如果要储存一千个学生的名字要怎么做呢?难道要写一千行代码吗?
答:…………
正是因为以上问题我们引进了一个特殊的数据类型,数组。
1. 数组
是指同一类型的一组值,属于引用类型,主要是运用对同一类型的数据进行批量处理。
如何声明并初始化数组:
int[] a={1,2,3,4,5,6};
int[]a1=new int[]{1,2,3,4,5};
int[]a2=new int[5]{1,2,3,4,5};
int[]a3=new int[5];
示例:接受五个学生的姓名,并将接受的数据存放到数组中,接受完成后进行输出。
string[] a = new string[5]{“甲“,”乙“,”丙“,”丁“,”戊“};
Console.WriteLine(a[5]);
Console.ReadKey();
2.二维数组
与一维数组类似,二维数组声明的一般格式如下:
int[,] b=new int[3,2];
例:int[,] b = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
Console.WriteLine(b[i,j]);
}
}
Console.ReadKey();
3.foreach(遍历器)
语法:
foreach(数据类型 变量 in集合或数组名称)
{
语句
}
foreach比for循环更加方便快捷。
例:
string[] a = new string[5]{“甲“,”乙“,”丙“,”丁“,”戊“};
foreach(string f in a )
{
Console.WriteLine(f);
}
Console.ReadKey();
更多精彩请到:http://www.gopedu.com/