為什么要引入集合?
因為數(shù)組有很多的局限性,以下舉三個最主要的
1.數(shù)組只能存取相同類型的數(shù)據(jù)比如int數(shù)組只能存int類型的數(shù)據(jù)
?2.數(shù)組存在大量的垃圾數(shù)據(jù)
?3.數(shù)組不能動態(tài)的擴展長度
因為數(shù)組的局限性,所以引入集合的概念。
Hashtable ht = new Hashtable();
Hashtable 的數(shù)據(jù)都是以鍵值對的形式出現(xiàn)
ht.add("key","value"); 往Hashtable 中加入元素
通過key取value
console.WriteLine(ht["key"]);
通過一個key移除一個值
ht.Remove("key");
全部清除
ht.Clear();
索引器
索引器:
?對于索引器,看起來有點像屬性,同樣有get,set方法,但是有區(qū)別
?1.索引器必須是實例成員,也就是不能加static,屬性可以是靜態(tài)成員
?2.索引器可以被重載,屬性不可以
?3.要使用this關鍵字來定義索引器
4.索引器不能用static修飾
索引器和數(shù)組比較:
(1)索引器的索引值(Index)類型不受限制
(2)索引器允許重載
(3)索引器不是一個變量
//這是我自己寫的索引器
class Person//需要索引的類,保存字段
{
public int Age;
public string Name;
public int Id;
public Person(string name,int age,int id)
{
Age = age;Name = name;Id = id;
}
}
//泛型索引器,引用泛型是為了免去裝箱和拆箱的操作
class PersonSelect{
Listlist<Person>= new List<Person>();//
//通過ID和年齡查找名字
public string this [int index, int age] {
set{ list.Add (new Person (value, age, index)); }
get {
foreach (Person p in list) {
if (p.Age == age && p.Id == index) {
return p.Name;
}
}
return "";
}
}
//通過名字和年齡查找ID
public int this[string name,int age]
{
get
{
foreach ( Person p in list) {
if (p.Name == name && p.Age == age) {
return p.Id;
}
}
return -1;
}
set{ list.Add (new Person (name, age, value));}
}
//還可以有更多的索引器
}
class MainClass
{
public static void Main (string[] args)
{
PersonSelect ps = new PersonSelect ();
ps [1, 2] = "A";
ps [2, 2] = "B";
ps [3, 3] = "C";
ps ["QQ", 1] = 2;
ps ["qq", 2] = 1;
Console.WriteLine (ps["QQ",1]+" "+ ps[1,2] + " "+ps["qq",2]);
}
}