转自http://www.cnblogs.com/nevernet/archive/2009/01/08/1371856.html
1.数组集合
其实,在数组的一节里面已经包含了这个概念了。其实数组集合就是 new int[2];
官方参考地址:http://msdn.microsoft.com/zh-cn/library/57yac89c(VS.80).aspx
2.ArrayList
ArrayList跟数组(Array)的区别:http://msdn.microsoft.com/zh-cn/library/41107z8a(VS.80).aspx
实例:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace CSharp
{
public class TestArrayList
{
public TestArrayList()
{
// Create an empty ArrayList, and add some elements.
ArrayList stringList = new ArrayList();
stringList.Add("a");
stringList.Add("abc");
stringList.Add("abcdef");
stringList.Add("abcdefg");
stringList.Add(20);
// 索引或者说数组下标是数字,所以不需要名字.
Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);
// 给下标为2的元素赋值
stringList[2] = "abcd";
Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);
// 输出stringList的总的元素个素
Console.WriteLine("Number of elements in the list: {0}",
stringList.Count);
try
{
//数组下标从0到count-1,如果尝试输出小于0或者大于等于count的下标,将抛出异常。
Console.WriteLine("Element {0} is \"{1}\"",
stringList.Count, stringList[stringList.Count]);
}
catch (ArgumentOutOfRangeException aoore)
{
Console.WriteLine("stringList({0}) is out of range(越界).",
stringList.Count);
}
// 不能使用这种方式来增加元素,只能通过stringList.add("aa")来增加元素
try
{
stringList[stringList.Count] = "42";
}
catch (ArgumentOutOfRangeException aoore)
{
Console.WriteLine("stringList({0}) is out of range(越界).",
stringList.Count);
}
Console.WriteLine();
//用for来循环
for (int i = 0; i < stringList.Count; i++)
{
Console.WriteLine("Element {0} is \"{1}\"", i,
stringList[i]);
}
Console.WriteLine();
//用foreach来循环
foreach (object o in stringList)
{
Console.WriteLine(o);
}
Console.ReadLine();
}
}
}
这里同时要提到StringCollection,其实这个跟ArrayList没啥区别,只不过StringCollection只能接收字符类型的东西。
官方地址:http://msdn.microsoft.com/zh-cn/library/system.collections.specialized.stringcollection(VS.80).aspx
0 评论:
发表评论