C# 中 []、List、Array、ArrayList 的区别及应用

泛型最常见的用途是泛型集合,命名空间System.Collections.Generic 中包含了一些基于泛型的集合类,使用泛型集合类可以提供更高的类型安全性,还有更高的性能,避免了非泛型集合的重复的装箱和拆箱。
很多非泛型集合类都有对应的泛型集合类,下面是常用的非泛型集合类以及对应的泛型集合类:
非泛型集合类 泛型集合类
ArrayList List<T>
HashTable DIctionary<T>
Queue Queue<T>
Stack Stack<T>
SortedListSortedList<T>

我们用的比较多的非泛型集合类主要有 ArrayList类 和 HashTable类。我们经常用HashTable 来存储将要写入到数据库或者返回的信息,在这之间要不断的进行类型的转化,增加了系统装箱和拆箱的负担,如果我们操纵的数据类型相对确定的化 用 Dictionary<TKey,TValue> 集合类来存储数据就方便多了,例如我们需要在电子商务网站中存储用户的购物车信息( 商品名,对应的商品个数)时,完全可以用 Dictionary<string, int> 来存储购物车信息,而不需要任何的类型转化。

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

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

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

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

Array 和 ArrayList 是通过存储 object 实现任意类型的,所以使用时要转换。

应用示例

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.Collections
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; // 需要类型转换
}
}
}


参考资料

http://www.cftea.com/c/2008/10/XNW6ZR0WXNGK6B9X.asp

http://home.51.com/chen249993213/diary/item/10044022.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值