IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    C# Dictionary容器练习

    abilitytao发表于 2014-09-22 11:06:00
    love 0
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    class MagicDictionary
    {

    private Dictionary dic;

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

    }

    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
    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);
    }

    }

    }


    abilitytao 2014-09-22 19:06 发表评论


沪ICP备19023445号-2号
友情链接