- 最后登录
- 2019-12-25
- 注册时间
- 2012-8-24
- 阅读权限
- 90
- 积分
- 71088
 
- 纳金币
- 52352
- 精华
- 343
|
C# 泛型集合之非泛型集合类与泛型集合类的对应: ArrayList对应List HashTable对应Dictionary Queue对应Queue Stack对应Stack SortedList对应SortedList 集合是进化的数组,数组有下标和元素,集合有key和value 1.数组是固定大小的,不能伸缩。虽然System.Array.Resize这个泛型方法可以重置数组大小,
但是该方法是重新创建新设置大小的数组,用的是旧数组的元素初始化。随后以前的数组就废弃!而集合却是可变长的
2.数组要声明元素的类型,集合类的元素类型却是object.
3.数组可读可写不能声明只读数组。集合类可以提供ReadOnly方法以只读方式使用集合。
4.数组要有整数下标才能访问特定的元素,然而很多时候这样的下标并不是很有用。集合也是数据列表却不使用下标访问。
很多时候集合有定制的下标类型,对于队列和栈根本就不支持下标访问! - using System;
- using System .Collections .Generic ;//泛型
- using System .Collections ;//非泛型
- namespace gather
- {
- class MainClass
- {
- public static void Main (string[] args)
- {
- ArrayList alist = new ArrayList ();//非泛型ArrayList可以传参数为object类型
- alist .Add (2);
- alist .Add ("xxx");
- alist .Add ("s");
- foreach (object item in alist) {
- Console.WriteLine (item);
- }
- List <string>slist = new List<string> ();//非泛型List可以传参数为规定类型<string>
- slist .Add ("xxssx");//添加元素
- slist .Add ("v");
- List <int>ilist = new List<int> ();//泛型List可以传参数为规定类型<string>
- ilist .Add (4);//添加元素
- ilist .Add (55);
- foreach (var ite in slist ) {//遍历
- Console.WriteLine (ite);
- }
- foreach (var item in ilist) {
- Console.WriteLine (item);
- }
- Hashtable hash = new Hashtable ();//非泛型Hashtable可以传参数为object类型key和object类型value
- hash .Add (3,"xxxww");
- hash .Add ("ed",44);
- hash .Add ("4","w");
- foreach (DictionaryEntry item in hash) {//Hashtable 内的每一组对象就是一个DictionaryEntry
- Console.WriteLine (item.Key );
- Console.WriteLine (item .Value );
- }
- foreach (var item in hash.Keys ) {//遍历key
- Console.WriteLine (item);
- }
- foreach (var item in hash.Values ) {//遍历value
- Console.WriteLine (item);
- }
- Dictionary <int ,int >dict =new Dictionary<int, int>();//泛型Dictionary可以传参数为规定类型<int,int>
- dict .Add (4,3);
- dict .Add (5,7);
- dict .Add (0,44);
- foreach (object item in dict ) {//遍历每一组对象
- Console.WriteLine (item);
- }
- foreach (var item in dict.Keys ) {//遍历key值
- Console.WriteLine (item);
- }
- foreach (var item in dict.Values ) {//遍历value值
- Console.WriteLine (item);
- }
- }
- }
- }
复制代码
其他集合方法
|
|