1.一维数组:
语法: 数据类型[] 数组名;
但是,这 样的命名是:数据类型 数组名[] 错误的。
- 在C#中我们可以通过下标,来访问数组的元素。语法:数组名[下标]。
- 通过数组的length属性,可以获得数组的长度。语法:数组名.Length.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShuZu
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[5] ;
int[] array = new int[5] { 0, 1, 2, 3, 4 };
int[] array1 = new int[] { 0, 1, 2, 3, 4 }; //省略数组长度
int[] array2 = { 0, 1, 2, 3, 4 }; //省略new关键字
Console.WriteLine("数组array的元素个数是{0}",array.Length);
Console.WriteLine("数组array1的元素个数是{0}", array1.Length);
Console.WriteLine("数组array2的元素个数是{0}", array2.Length);
}
}
}
2.对象数组:
对象数组就是数组里的每个元素都是类的对象,赋值时先定义对象,然后将对象直接赋给数组就行了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShuZu
{
class Program
{
static void Main(string[] args)
{
//定义对象数组
Student[] student = new Student[3];
//为对象数组元素赋值
student[0] = new Student();
student[0].name = "张海";
student[0].score = 98;
student[1] = new Student();
student[1].name = "李成";
student[1].score = 96;
student[2] = new Student();
student[2].name = "江一";
student[2].score = 96;
foreach (Student stu in student)
{
stu.showInfo();
}
Console.Read();
}
}
}