









集合提供了一种将任意对象格式化存储的方法,一个集合可以被定义为一个实现了一个或多个System.Collections.ICollection、System.Collections.IDictionary和System.Collections.IList的对象。以下是一些常用的.Net内部的集合:
ArrayList
当需要大小可按需动态增加,并希望通过索引来进行访问的数组的时候,使用ArrayList
ArrayList myAL = new ArrayList();
myAL.Add("Hello");
myAL.Add("World");
myAL.Add("!");
Console.WriteLine(myAL[0] + myAL[1] + myAL[2]
Stack
当需要一个能实现后进先出的集合时,使用Stack
// Creates and initializes a new Stack.
Stack myStack = new Stack();
myStack.Push("Hello");
myStack.Push("World");
myStack.Push("!");
// Displays the properties and values of the Stack.
Console.WriteLine( "myStack" );
Console.WriteLine( "\tCount: {0}", myStack.Count );
Console.Write( "\tValues:" );
System.Collections.IEnumerator myEnumerator = myStack.GetEnumerator();
while ( myEnumerator.MoveNext() )
Console.Write( "\t{0}", myEnumerator.Current);
Console.WriteLine();
Queue
当需要一个先进先出的集合时,使用Queue
// Creates and initializes a new Queue.
Queue myQ = new Queue();
myQ.Enqueue("Hello");
myQ.Enqueue("World");
myQ.Enqueue("!");
// Displays the properties and values of the Queue.
Console.WriteLine( "myQ" );
Console.WriteLine( "\tCount: {0}", myQ.Count );
Console.Write( "\tValues:" );
Hashtable
当需要一个可以按Key值来查询的数组是,使用Hashtable
// Creates and initializes a new Hashtable.
Hashtable myHT = new Hashtable();
myHT.Add("First", "Hello");
myHT.Add("Second", "World");
myHT.Add("Third", "!");
// Displays the properties and values of the Hashtable.
Console.WriteLine( "myHT" );
Console.WriteLine( "\tCount: {0}", myHT.Count );
Console.WriteLine( "\t Values:" );
IDictionaryEnumerator myEnumerator = myHT.GetEnumerator();
Console.WriteLine( "\t-KEY-\t-VALUE-" );
while ( myEnumerator.MoveNext() )
Console.WriteLine("\t{0}:\t{1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
当然,除了.Net自定义的这些集合外,也可以通过实现IList,ICollection,IEnumerable来定义自己集合类,如:DataTable.Rows就是实现ICollection,IEnumerable接口。但这样的工作比较繁琐,需要实现的方法很多,还要考虑存储和索引,所以通常的做法是直接继承自ArrayList , Stack , Queue , HashTable,进一步封装,如:
public class Users:ArrayList
{
public Users()
{
}
public new User this[int index]
{
get
{
return (User)(base[index]);
}
set
{
base[index] = value;
}
}
public int Add(User value)
{
return base.Add(value);
}
}
public class User
{
public User()
{
//
// TODO: Add constructor logic here
//
}
private string m_strName;
private int m_intAge;
private string m_strEmail;
public string Name
{
get
{
return this.m_strName;
}
set
{
this.m_strName = value;
}
}
public int Age
{
get
{
return this.m_intAge;
}
set
{
this.m_intAge = value;
}
}
public string Eamil
{
get
{
return this.m_strEmail;
}
set
{
this.m_strEmail = value;
}
}
}
这样既增加了可读性,实现起来也容易,使用起来也方便,可以直接使用objUsers[0].Name来访问
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。