The Fourth Dimension Space

枯叶北风寒,忽然年以残,念往昔,语默心酸。二十光阴无一物,韶光贱,寐难安; 不畏形影单,道途阻且慢,哪曲折,如渡飞湍。斩浪劈波酬壮志,同把酒,共言欢! -如梦令

C# Dictionary容器练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class MagicDictionary
{

    private Dictionary<String, String> dic;

    public MagicDictionary()
    {
        dic = new Dictionary<stringstring>();

    }

    void Add(String key, String value)
    {
        if (dic.ContainsKey(key)&&dic[key]==value)
            throw new Exception("KeyValuePair already exsits");
        dic.Add(key, value);
    }

    void Remove(String key)
    {
        if (!dic.ContainsKey(key))
            throw new Exception("it doesn't exsit");
        dic.Remove(key);
    }

    void Set(String key, String value)
    {
        if (dic.ContainsKey(key))
            dic[key] = value;
        else
            dic.Add(key, value);
    }

    String Get(String key)
    {
        return dic[key];
    }

    void PrintAll()
    {
        foreach (KeyValuePair<String, String> i in dic)
        {
            Console.WriteLine(i.Key + " " + i.Value);
        }
    }

    String TryGetValue(String key)
    {
        if (dic.ContainsKey(key))
            return dic[key];
        else
            return "";
    }

    public String this[String key]
    {
        set
        {
            dic[key] = value;
        }
        get
        {
            return dic[key];
        }
    }

    public static void Main()
    {

        try
        {
            MagicDictionary t = new MagicDictionary();
            t.Add("Hi", "Hello");
          //  t.Add("Hi", "Hello");
            t.Add("What", "ever");
            t.Add("Pretty", "Girl");
            t.Add("Apple", "Google");
            t.PrintAll();
            t.Remove("Pretty");
            t.Remove("#$@#*$");
            t.Set("What", "Whatever");
            if (t.TryGetValue("Hi") != "")
                Console.WriteLine("OK");
            else
                Console.WriteLine("Bu OK");

            if (t.TryGetValue("Appoe") != "")
                Console.WriteLine("OK");
            else
                Console.WriteLine("Bu OK");
            Console.WriteLine(t.Get("Apple"));
            t["Apple"] = "BIG GOOGLE";

            t.PrintAll();
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.Message);
        }

    }

}

posted on 2014-09-22 19:06 abilitytao 阅读(397) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理