C#数组
时间:2011-03-20 来源:任银
简单数组:
1 int[] myArray = new int[4];2 int[] myArray = new int[4]{4,7,11,2};
3 int[] myArray = new int[]{4,7,11,2};
4 int[] myArray = {4,7,11,2};
5 Person[] myPerson = {new Person("A"),new Person("B")};
多维数组:
int[,] twodim = new int[3,3];twodim[0,0] = 1;
twodim[0,1] = 2;
twodim[1,1] = 3;
...
twodim[2,2] = 9;
int[,] twodim = {
{1,2,3},
{4,5,6}
}
int[,,] threedim = {
{{1,2},{3,4}},
{{5,6},{7,8}},
{{9,10},{11,12}}
}
锯齿数组:
1 int[][] jagged = new int[3][];2 jagged[0] = new int[2]{1,2};
3 jagged[1] = new int[6]{3,4,5,6,7,8};
4 jagged[2] = new int[3]{9,10,11};
Array类:
C#数组都是派生于抽象类基类Array的,可使用Array类为每个C#数组定义方法和属性。
Array类是一个抽象类,不能使用构造函数来创建数组,使用静态方法CreateInstance()创建数组
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Array类
{
public class Person
{
public Person()
{
}
public Person(string firstName, string lastName)
{
this.Firstname = firstName;
this.Lastname = lastName;
}
public string Firstname { get; set; }
public string Lastname { get; set; }
public override string ToString()
{
return String.Format("{0} {1}", Firstname, Lastname);
}
}
class Program
{
static void Main(string[] args)
{
#region Array创建数组
//创建元素类型为整形,长度为5的数组
Array intArray1 = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
{
//设置值
intArray1.SetValue(33, i);
}
for (int i = 0; i < 5; i++)
{
//获取值
Console.WriteLine(intArray1.GetValue(i));
}
#endregion
Console.WriteLine("------------------------");
Console.WriteLine("------------------------");
#region 转换数组类型
int[] intArray2 = (int[])intArray1;
foreach (int val in intArray2)
{
Console.WriteLine(val);
}
#endregion
Console.WriteLine("------------------------");
Console.WriteLine("------------------------");
#region CreateInstance的重载方法
//2*3的二维数组
int[] lengths = { 2, 3 };
//第1维基于1 第2维基于10
int[] lowerBounds = { 1, 10 };
//CreateInstance的重载 创建指定维数和下限的数组
Array racers = Array.CreateInstance(typeof(Person), lengths, lowerBounds);
//SetValue()方法设置数组的元素,其参数是每一维的索引
racers.SetValue(new Person("Alain", "Prost"), 1, 10);
racers.SetValue(new Person("Emerson", "Fittipaldi"), 1, 11);
racers.SetValue(new Person("Ayrton", "Senna"), 1, 12);
racers.SetValue(new Person("Ralf", "Schumacher"), 2, 10);
racers.SetValue(new Person("Fernando", "Alonso"), 2, 11);
racers.SetValue(new Person("Jenson", "Button"), 2, 12);
#endregion
}
}
}
未完待续...
相关阅读 更多 +