·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> C#数组之[]、List、Array、ArrayList应用

C#数组之[]、List、Array、ArrayList应用

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
PRotected void Page_Load(object sender, EventArgs e)
{
// System.Int32 是结构
int[] arr = new int[] { 1, 2, 3 };
Response.Write(arr[0]); // 1
Change(arr);
Response.Write(arr[0]); // 2

// List 的命名空间是 System.Collections.Generic
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
Response.Write(list[0]); // 1
Change(list);
Response.Write(list[0]); // 2

// Array 的命名空间是 System
Array array = Array.CreateInstance(System.Type.GetType("System.Int32"), 3); // Array 是抽象类,不能使用 new Array 创建。
array.SetValue(1, 0);
array.SetValue(2, 1);
array.SetValue(3, 2);
Response.Write(array.GetValue(0)); // 1
Change(array);
Response.Write(array.GetValue(0)); // 2

// ArrayList 的命名空间是 System.Collectio(www.111cn.net)ns
ArrayList arrayList = new ArrayList(3);
arrayList.Add(1);
arrayList.Add(2);
arrayList.Add(3);
Response.Write(arrayList[0]); // 1
Change(arrayList);
Response.Write(arrayList[0]); // 2
}

private void Change(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] *= 2;
}
}

private void Change(List<int> list)
{
for (int i = 0; i < list.Count; i++) // 使用 Count
{
list[i] *= 2;
}
}


private void Change(Array array)
{
for (int i = 0; i < array.Length; i++) // 使用 Length
{
array.SetValue((int)array.GetValue(i) * 2, i); // 需要类型转换
}
}

private void Change(ArrayList arrayList)
{
for (int i = 0; i < arrayList.Count; i++) // 使用 Count
{
arrayList[i] = (int)arrayList[i] * 2; // 需要类型转换
}
}
}

[] 是针对特定类型、固定长度的。

List 是针对特定类型、任意长度的。

Array 是针对任意类型、固定长度的。

ArrayList 是针对任意类型、任意长度的。

Array 和 ArrayList 是通过存储 object 实现任意类型的,所以使用时要转换
from:http://www.111cn.net/net/160/40651.htm