NameValueCollection 相當於 Key 和 Value 都是字串的且能通過索引訪問的雜湊表.
主要成員:
/* 屬性 */AllKeys; //返回包含所有鍵的 string[]Count; //Keys; //鍵集合/* 方法 */Add(); //Clear(); //CopyTo(); //Get(); //根據索引或鍵取值, 有多個值時會用逗號隔開GetKey(); //根據索引取鍵GetValues(); //根據索引或鍵取值, 返回 string[]HasKeys(); //是否包含非 null 鍵Remove(); //根據鍵移除Set(); //改值; 若鍵不存在則同 Add()
其 Key 可為 null, 且可對應多個 Value:
protected void Button1_Click(object sender, EventArgs e){ NameValueCollection nv = new NameValueCollection(); nv.Add("k1", "AAA"); nv.Add("k2", "BBB"); nv.Add("k3", "CCC"); nv.Add(null, "DDD"); nv.Add("k2", "b"); nv.Add("k2", "bb"); nv.Add("k2", "bbb"); string str1 = nv["k1"]; //AAA string str2 = nv["k2"]; //BBB,b,bb,bbb : 多個值會用逗號分開 string str3 = nv[1]; //BBB,b,bb,bbb string str4 = nv[null]; //DDD TextBox1.Text = str1 + "\n" + str2 + "\n" + str3 + "\n" + str4;}
練習:
protected void Button1_Click(object sender, EventArgs e){ NameValueCollection nv = new NameValueCollection(); nv.Add("k1", "AAA"); nv.Add("k2", "BBB"); nv.Add("k3", "CCC"); nv.Add("k2", "b"); nv.Add("k2", "bb"); nv.Add("k2", "bbb"); int n = nv.Count; //3 : k1、k2、k3 nv.Set("k1", "aaa"); string str1 = nv.Get(0); //aaa string str2 = nv.Get("k1"); //aaa string str3 = nv.GetKey(0); //k1 string[] sArr1 = nv.GetValues(0); string[] sArr2 = nv.GetValues("k2"); string str4 = string.Join("; ", sArr1); //aaa string str5 = string.Join("; ", sArr2); TextBox1.Text = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}", n, str1, str2, str3, str4, str5);}protected void Button2_Click(object sender, EventArgs e){ NameValueCollection nv = new NameValueCollection(); nv.Add("k1", "AAA"); nv.Add("k2", "BBB"); nv.Add("k3", "CCC"); nv.Add("k2", "b"); nv.Add("k2", "bb"); nv.Add("k2", "bbb"); NameValueCollection.KeysCollection keys = nv.Keys; string str1 = ""; foreach (string s in keys) { str1 += s + ", "; } //k1, k2, k3, string str2 = string.Join("; ", nv.AllKeys); //k1; k2; k3 TextBox1.Text = str1 + "\n" + str2;}