C#中的Hashtable,

后面的开发中,不建议使用Hashtable进行开发,

而是采用Dictionary<TKey, TValue>泛型进行开发

简单列一个代码介绍Hashtable


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


//Hashtable 
//哈希表,是键值对的集合,,
//每个元素都是一个存储在DictionaryEntry对象中的键/值对
//键不能维空引用
//DictionaryEntry结构包含两个属性:Key和Value,
//分别表示键和值。通过遍历Dictionary集合的元素,
//可以使用DictionaryEntry来访问每个键值对的具体数据。

namespace HashTableDemo01
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //HashTable的构造函数
            //public HashTable()使用默认的初始容量,加载因子、哈希代码
            //提供程序和比较器来初始化HashTable类的新空实列
            //public HashTable(int Capacity)
            //Capacity最初可包含的元素的近似数目

            //在System.Collections命名空间中
            Hashtable ht = new Hashtable();

            //public virtual void Add(Object key, Object value)
            //key要添加的元素的键
            //value要添加的元素的值,值可以为空引用
            ht.Add("1", "Deng");
            ht.Add("2", "Yong");
            ht.Add("3", "Jian");
            ht.Add("4", "Hello");
            ht.Add("5", "World");


            //Hashtable的遍历
            foreach( DictionaryEntry dicEntry in ht)
            {
                Console.WriteLine("\t" + dicEntry.Key + ": " + dicEntry.Value); 
            }
            Console.WriteLine();

            //Remove方法从Hashtable中移除嗲有指定键的元素
            //public virtual void Remove(Object obj)
            ht.Remove("2");
            //Hashtable的遍历
            foreach (DictionaryEntry dicEntry in ht)
            {
                Console.WriteLine("\t" + dicEntry.Key + ": " + dicEntry.Value);
            }
            Console.WriteLine();

            //public virtual void clear()
            //从Hashtable中移除所有的元素
            ht.Clear();

            Console.WriteLine("Hashtable中的元素个数为:{0} ", ht.Count);

            ht.Add("A", "DENG");
            ht.Add("B", "YONG");
            ht.Add("C", "JIAN");
            ht.Add("D", "HELLO");
            ht.Add("E", "WORLD");
            ht.Add("1", "HIYO");
            ht.Add("2", "STUDIOS");
            ht.Add("3", "INDUSTRY");
            ht.Add("4", "DEISGNER");

            //遍历
            foreach(DictionaryEntry de in ht)
            {
                Console.WriteLine("\t" + de.Key + ": " + de.Value);
            }
            Console.WriteLine("哈希表中含有的键值对数:" + ht.Count);

            //Hashtable元素的查找
            //public virtual bool Contains(Object key)
            //用来确定Hashtable中是否包含特定键


            //不建议使用 Hashtable 类进行新开发。
            //建议改用 泛型 Dictionary<TKey,TValue> 类
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值