泛型和非泛型
一:区别
1 : 非泛型类容器来说,该容器的元素类型是 object ,使用方便,无须指定具体的元素类型。但是这种使用上的方便带来了惨重的性能上的损失,因为,我们每次插入一个元素就要经过一次 “ 装箱 ” 操作,每次访问一个元素就要经过一次 “ 拆箱 ” 操作。
ArrayList , Hashtable , Queue , Stack , SortedList , CollectionBase , ReadOnlyCollectionBase 。
2 : “ 泛型 ” 容器就不一样了,这种类型的容器和 C++ 里的容器 ( 比如 vector 、 map 、 list 等 ) 一样,在使用的时候都要指定元素类型,并且在 “ 编译阶段 ” 完成类型制定,而且也避免了 “ 装箱、拆箱、类型转换 ” 等无谓的性能损失。
List , Dictonary , Queue , Stack , SortedList , Collection , ReadOnlyCollection 。
二:如何选择集合类
1 : FIFO : Queue 。 LIFO : Stack 。
2 :按索引访问: ArrayList , List 。
3 :按索引键访问: Hashtable , SortedList , Dictonary 。 Hashtable 对于大量数据如几万,几十万时,数据搜索效率高。 SortedList 一般用在几百,几千条数据时用。
三:SortedList键值允许重复
struct SortedListValue
{
public SortedListValue(int a, int b)
{
this.a = a;
this.b = b;
}
public int a;
public int b;
}
class MyComparer : IComparer
{
#region IComparer Members
//希望键值重复的话,就不能返回0
public int Compare(object x, object y)
{
int a = (int)x;
int b = (int)y;
if (a.Equals(b))
{
return -1;
}
return a.CompareTo(b);
}
#endregion
}
class Program
{
static void Main(string[] args)
{
SortedList sl = new SortedList(new MyComparer());
sl.Add(1, new SortedListValue(1, 2));
sl.Add(2, new SortedListValue(3, 2));
sl.Add(3, new SortedListValue(2, 2));
sl.Add(1, new SortedListValue(4, 2));
sl.Add(1, new SortedListValue(5, 2));
sl.Add(2, new SortedListValue(1, 2));
DisplayResult(sl);
}
static void DisplayResult(SortedList sl)
{
foreach (DictionaryEntry de in sl)
{
Console.WriteLine("键:{0},键值为:{1}", de.Key, ((SortedListValue)(de.Value)).a);
}
}
}
}