c#进阶 Hashtable

using System;
using System.Collections;

namespace Lesson4_HashTable
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("HshTable");
            #region 知识点一 Hashtable的本质
            //Hashtable(又称散列表)是基于键的哈希代码组织起来的键/值对
            //它的主要作用是提高数据查询的效率
            //使用键来访问集合中的元素
            #endregion
            #region 知识点二 声明
            Hashtable hash = new Hashtable();
            #endregion
            #region 知识点三 增删改查
            #region 增
            hash.Add(1, "123");
            hash.Add("123", 2);
            hash.Add(true, false);
            hash.Add(false, true);
            hash.Add(2, "1");
            hash.Add(3, "1");
            hash.Add(4, "1");
            hash.Add(5, "1");
            hash.Add(6, "1");
            //不能出现相同的键
            #endregion
            #region 删
            //1.只能通过键去删除
            hash.Remove(1);
            //2.删除不存在的键,无影响
            hash.Remove(2);
            //3.直接清空
            hash.Clear();
            #endregion
            #region 查
            //1.通过键查看值
            //找不到返回空
            Console.WriteLine(hash[1]);
            Console.WriteLine(hash[999]);//null
            //2.查看是否存在
            //根据键检测
            if (hash.ContainsKey(1) || hash.Contains(2))
            {
                Console.WriteLine("Exits");
            } else
            {
                Console.WriteLine("No exits");
            }

            //根据值检测
            if (hash.ContainsValue("1"))
            {
                Console.WriteLine("Exits");
            } else
            {
                Console.WriteLine("No exits");
            }
            #endregion
            #region 改
            //只能通过键修改值,不能修改键
            hash[1] = 123;
            Console.WriteLine(hash[1]);
            hash[2] = 456;
            Console.WriteLine(hash[2]);
            #endregion
            #endregion
            #region 知识点四 遍历
            //得到元素数量(对数)
            int len = hash.Count;

            //1.遍历所有键
            foreach(object item in hash.Keys)
            {
                Console.WriteLine(item);
            }
            
            //2.遍历所有值
            foreach(object item in hash.Values) {
                Console.WriteLine(item);
            }

            //3.键值一起遍历
            //使用DictionnaryEntry
            foreach(DictionaryEntry item in hash)
            {
                Console.WriteLine(item.Key + " " + item.Value);
            }

            //4.使用迭代器遍历
            IDictionaryEnumerator it = hash.GetEnumerator();
            bool flag = it.MoveNext();
            while (flag)
            {
                Console.WriteLine(it.Key + " " + it.Value);
                flag = it.MoveNext();
            }
            #endregion
            #region 知识点五 装箱拆箱
            //由于用万物之父来存储数据,自然存在装箱拆箱。
            //当往其中进行值类型存储时就是在装箱
            //当将值类型对象取出来转换使用时,就存在拆箱。
            #endregion
        }
    }
}