close


            // Create a new dictionary of strings, with string keys.
            Dictionary openWith =
                new Dictionary();

            // Add some elements to the dictionary. There are no 
            // duplicate keys, but some of the values are duplicates.
            openWith.Add("txt", "notepad.exe");
            openWith.Add("bmp", "paint.exe");
            openWith.Add("dib", "paint.exe");
            openWith.Add("rtf", "wordpad.exe");

            // To get the TValue of rtf(TKey)
            Console.WriteLine("For key = \"rtf\", value = {0}.",
            openWith["rtf"];

            // The indexer can be used to change the value associated
            // with a key.
            openWith["rtf"] = "Alamword.exe";
            Console.WriteLine("For key = \"rtf\", value = {0}.",
                openWith["rtf"]);

            // The Add method throws an exception if the new key is 
            // already in the dictionary.
            try
            {
                openWith.Add("txt", "winword.exe");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("An element with Key = \"txt\" already exists.");
            }

            // If a key does not exist, setting the indexer for that key
            // adds a new key/value pair.
            // method(1) The indexer throws an exception if the requested key is
            // not in the dictionary.
            try
            {
                Console.WriteLine("For key = \"tif\", value = {0}.",
                    openWith["tif"]);
            }
            catch (KeyNotFoundException)
            {
                Console.WriteLine("Key = \"tif\" is not found.");
            }
            // method(2) When a program often has to try keys that turn out not to
            // be in the dictionary, TryGetValue can be a more efficient 
            // way to retrieve values.
            string value = "";
            if (openWith.TryGetValue("tif", out value))
            {
                Console.WriteLine("For key = \"tif\", value = {0}.", value);
            }
            else
            {
                Console.WriteLine("Key = \"tif\" is not found.");
                //Console.ReadLine();
            }

參考資料:在Blog中放入程式碼

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 imagefish 的頭像
    imagefish

    幻想魚的幻想空間

    imagefish 發表在 痞客邦 留言(0) 人氣()