欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hashtable哈希表及其与Dictionary字典的区别

程序员文章站 2024-03-23 13:08:04
...

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