bloggerAds

2015年8月31日 星期一

Dictionary

字典,顧名思義,
可以藉由一個key值索引到相對應的value;
雖然 Dictionary與陣列相似,
但好處是可以動態的增加或是移除資料。
讓我們透過範例來認識認識它唄!

Example:
先引用:
using System.Collections.Generic;

Example1:新增與查詢
void Start () {
    //依需求作宣告,Dictionary<"Key的型態" ,"Value的型態" >
    //本次範例為宣告成員的年齡,以名字(string型態)為Key,年紀(int 型態)為value

    Dictionary<string ,int> MembersAgeDic = new Dictionary<string, int>();
    MembersAgeDic.Add ("Wilson",26);
    MembersAgeDic.Add ("John",18);
    MembersAgeDic.Add ("Mary",16);
    MembersAgeDic.Add ("Tom",20);

    Debug.Log ("Wilson age is " + MembersAgeDic["Wilson"]);
    Debug.Log ("Tom age is "    + MembersAgeDic["Tom"]);
}
//--------output
Wilson age is 26
Tom age is 20
//--------------------

Example2:直接給予Key值與Value
void Start () {
    Dictionary<string ,int> MembersAgeDic = new Dictionary<string, int>();
    MembersAgeDic["Wilson"] = 26;
    MembersAgeDic["Wilson"] = 40;
    MembersAgeDic["Tom"]    = 20;

    Debug.Log ("Wilson age is " + MembersAgeDic["Wilson"]);
    Debug.Log ("Tom age is "    + MembersAgeDic["Tom"]);
}
//--------output
Wilson age is 40
Tom age is 20
//--------------------

Example3:查詢該值是否存在
//部分程式碼
MembersAgeDic["Wilson"] = 26;
MembersAgeDic["Tom"]    = 20;

Debug.Log ("Is Have Wilson Age? " + MembersAgeDic.ContainsKey("Wilson"));
Debug.Log ("Is Have Bob Age? "    + MembersAgeDic.ContainsKey("Bob"));
//output
Is Have Wilson Age? True
Is Have Bob Age? False
//---------

常見錯誤1:重複給予相同的Key值

在Add時須注意是否該Key值被重複新增,
重複新增時將導至執行出錯
//部分程式碼
MembersAgeDic.Add ("Wilson",26);
MembersAgeDic.Add ("Wilson",40);
//--------output
ArgumentException: An element with the same key already exists in the dictionary.
//--------------------

常見錯誤2:搜尋不存在的Key值
//部分程式碼
MembersAgeDic["Wilson"] = 26;
Debug.Log ("Bob age is "    + MembersAgeDic["Bob"]); //未曾宣告Bob與其年紀
//--------output
KeyNotFoundException: The given key was not present in the dictionary
//--------------------

沒有留言:

張貼留言