IDictionary与TryGetValue

using System;
using System.Collections.Generic;

namespace net.howsoftworks
{
    class TryGetValue
    {
        static void Main(string[] args)
        {
            IDictionary<string, string> dict = new Dictionary<string, string>();
            dict["java"] = "c sharp";
            dict.Add("c++", "c plus plus");
            dict["c#"] = "dot net";

            foreach (var v in dict)
            {
                Console.WriteLine(v);
            }

            string val;
            Console.WriteLine("dict.TryGetValue('c#') = " +
                dict.TryGetValue("c#", out val));
            Console.WriteLine("val = " + val);

            Console.WriteLine("dict['c#'] = " + val);
            Console.WriteLine("dict.TryGetValue('java') = " +
                dict.TryGetValue("java", out val));

            try
            {
                dict.TryGetValue(null, out val);
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("\nEx1. " + e.Message);
            }

            try
            {
                val = dict[null];
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("Ex2. " + e.Message);
            }

            try
            {
                val = dict["java"];
            }
            catch (KeyNotFoundException e)
            {
                Console.WriteLine("Ex3. " + e.Message);
            }
            Console.Read();
        }
    }
}

 

posted on 2014-12-09 21:37  刘顺利  阅读(338)  评论(0)    收藏  举报

导航