【C#】Hashtable哈希表及其与Dictionary字典的区别

Hashtable哈希表:

看起来与Dictionary何止是相似啊

Hashtable与Dictionary,都是key/value键值对的形式,区别在于Hashtable的键值是object(DictionaryEntry),值类型,数据排列是乱序的;而Dictionary是泛型(KeyValuePair<T, T>),引用类型,按插入顺序排列数据

Hashtable相对于Dictionary,在使用Hashtable需要装箱拆箱操作进行格式转换,用起来不够方便,不过在大批量数据的随机检索(无规律)时,Hashtable更有优势。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{

    void Start()
    {
        Hashtable hashtable = new Hashtable();

        hashtable.Add("name", 1);

        foreach (var item in hashtable)
        {
            Debug.Log(item);
            //打印结果:"System.Collections.DictionaryEntry"
        }
        foreach (DictionaryEntry item in hashtable)
        {
            Debug.Log(item.Key + " : " + item.Value);
            //打印结果:"name : 1"
        }
        foreach (KeyValuePair<object, object> item in hashtable)
        {
            Debug.Log(item.Key + " : " + item.Value);
            //打印结果:"InvalidCastException: Specified cast is not valid."(报错强转无效)
        }


        Dictionary<string, int> dic = new Dictionary<string, int>();

        dic.Add("name", 1);

        foreach (KeyValuePair<string, int> item in dic)
        {
            Debug.Log(item.Key + " : " + item.Value);
        }
    }
}
public struct DictionaryEntry
{
	public object Key {
		get;
		set;
	}

	public object Value {
		get;
		set;
	}

	public DictionaryEntry (object key, object value);
}
发布了104 篇原创文章 · 获赞 74 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_39108767/article/details/103198267