数组的创建和访问
数组是具有索引的同类型的对象的集合,在C#中数组都是对象,所以它们都有各种方法和属性。数组是引用类型,在堆中创建数组创建后会分配给引用类型数组的内存将存放着对实际元素的引用。
C#提供Arrary的内置语法,创建数组实际上就是创建了System.Arrary类型的对象。
当我们创建一个值类型的数组以后,每个元素最最初都存放数组所属类型的默认值。
Code
则intArrary[i]默认值就是0。
与值类型数组不同,数组中的引用类型不能初始化默认值,它们会初始化为null。如果在我们特地初始化引用类型数组之前,访问数组,就会出现异常。
下面例子创建一个值类型数组和引用类型数组,分别用for语句和foreach语句对它们进行初始化和输出。
using System;
using System.Collections.Generic;
using System.Text;
namespace 处理数组
{
public class Employee
{
private int empID;
// 建立构造函数,初始化empID
public Employee(int empID)
{
this.empID = empID;
}
public override string ToString()
{
return empID.ToString();
}
}
class Program
{
static void Main(string[] args)
{
int[] intArrary;
Employee[] empArrary;
intArrary = new int[5];
empArrary = new Employee[3];
//填充数组
for (int i = 0; i < empArrary.Length; i++)
{
empArrary[i] = new Employee(i + 9);
}
for (int i = 0; i < intArrary.Length; i++)
{
intArrary[i] = i;
}
//输出
Console.WriteLine("for 访问");
for (int i = 0; i < intArrary.Length; i++)
{
Console.WriteLine(intArrary[i].ToString());
}
for (int i = 0; i < empArrary.Length; i++)
{
Console.WriteLine(empArrary[i].ToString());
}
Console.WriteLine("foreach 访问");
foreach (int i in intArrary)
{
Console.WriteLine(i.ToString());
}
foreach (Employee emp in empArrary)
{
Console.WriteLine(emp.ToString());
}
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace 处理数组
{
public class Employee
{
private int empID;
// 建立构造函数,初始化empID
public Employee(int empID)
{
this.empID = empID;
}
public override string ToString()
{
return empID.ToString();
}
}
class Program
{
static void Main(string[] args)
{
int[] intArrary;
Employee[] empArrary;
intArrary = new int[5];
empArrary = new Employee[3];
//填充数组
for (int i = 0; i < empArrary.Length; i++)
{
empArrary[i] = new Employee(i + 9);
}
for (int i = 0; i < intArrary.Length; i++)
{
intArrary[i] = i;
}
//输出
Console.WriteLine("for 访问");
for (int i = 0; i < intArrary.Length; i++)
{
Console.WriteLine(intArrary[i].ToString());
}
for (int i = 0; i < empArrary.Length; i++)
{
Console.WriteLine(empArrary[i].ToString());
}
Console.WriteLine("foreach 访问");
foreach (int i in intArrary)
{
Console.WriteLine(i.ToString());
}
foreach (Employee emp in empArrary)
{
Console.WriteLine(emp.ToString());
}
Console.ReadLine();
}
}
}
使用params关键字:
使用params关键字我们不必现实创建数组就能传入可变数的参数,可以将任意多的数组传入,然后作相关操作(例如输出控制台)。
public static void DisplayVals(params Employee[] emp)
{
foreach (Employee e in emp)
{
Console.WriteLine(e.empID.ToString());
}
}
{
foreach (Employee e in emp)
{
Console.WriteLine(e.empID.ToString());
}
}
控制台输出:
Employee.DisplayVals(empArrary);
测试方法声明然后初始化了两个数组,如果不过整数数组进行循环赋值,则数组自动初始化为0。Employee数组的内容要手工构造。