hashtable 会将所有的类型全部转为对象,所以能存各种类型,换句话说item的类型可能不同,这样的话可能会造成风险,Dictionary因为有泛型限制,所以编译器会校验item的类型,如果类型不同编译阶段会报错,
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace hashtable和Dictionary的泛型实验
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1,1);
ht.Add("1","1");
foreach (var item in ht.Keys)
{
Console.WriteLine("Key = {0},Value = {1}", item,ht[item]);
}
System.Threading.Thread.Sleep(2000);
Console.WriteLine("------------------------------");
Dictionary<String, String> d = new Dictionary<string, string>();
d.Add("a","1");
d.Add("A","1");
foreach (var item in d.Keys)
{
Console.WriteLine("Key = {0},Value = {1}", item, d[item]);
}
System.Threading.Thread.Sleep(2000);
}
}
}