有人知道System.Collections.Specialized.StringDictionary对象和System.Collections.Generic.Dictionary之间实际的区别吗?
我以前都用过它们,但从未考虑过哪一个性能更佳、在Linq中工作更好或提供其他任何优点。
有任何想法或建议可以告诉我为什么应该使用其中之一吗?
有人知道System.Collections.Specialized.StringDictionary对象和System.Collections.Generic.Dictionary之间实际的区别吗?
我以前都用过它们,但从未考虑过哪一个性能更佳、在Linq中工作更好或提供其他任何优点。
有任何想法或建议可以告诉我为什么应该使用其中之一吗?
Dictionary<string, string>
是一种更现代的方法。它实现了IEnumerable<T>
接口,更适合于LINQ风格的操作。
StringDictionary
是旧的方式。它存在于泛型时代之前。我只会在与旧代码进行接口时使用它。
另外一点。
这将返回 null:
StringDictionary dic = new StringDictionary();
return dic["Hey"];
这会抛出一个异常:
Dictionary<string, string> dic = new Dictionary<string, string>();
return dic["Hey"];
[]
。使用StringDictionary已经清理了我的大部分代码。 - James Curran[ ]
,因为它会抛出异常。(StringDictionary只能解决一种类型的字典问题) - James Currandefault(TValue)
,那么就不可能区分字典是否具有Value
为default(TValue)
的项或不包含与Key
匹配的KeyValuePair
。这就是为什么大多数情况下使用TryGetValue
是有意义的原因。请注意,可以通过使用((IDictionary)dic)["Hey"];
来获得不抛出异常的行为,但只应针对参考类型(如果有的话)进行此操作。 - NightOwl888正如Reed Copsey所指出的那样,StringDictionary会将你的键值转为小写。这对我来说是完全意外的,并且是一个致命问题。
private void testStringDictionary()
{
try
{
StringDictionary sd = new StringDictionary();
sd.Add("Bob", "My name is Bob");
sd.Add("joe", "My name is joe");
sd.Add("bob", "My name is bob"); // << throws an exception because
// "bob" is already a key!
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我在添加此回复以引起更多关注,因为我认为这个巨大的差异比现代与老派的区别更为重要。
Dictionary ht = new Dictionary(StringComparer.OrdinalIgnoreCase);
ht.Add("Bob", "ff");
ht.Add("bob", "ff"); // 抛出异常
- osexpertStringDictionary
可以在 Properites.Settings
中使用,而 Dictionary<string, string>
则不行。因此,无论是否过时,StringDictionary
仍然有一些用途。 - jahuStringDictionary
来自 .NET 1.1,并实现了 IEnumerable
Dictionary<string, string>
来自 .NET 2.0,并实现了 IDictionary<TKey, TValue>,IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
在 StringDictionary
中,IgnoreCase 只适用于 Key
Dictionary<string, string>
对于 LINQ 很好用
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("ITEM-1", "VALUE-1");
var item1 = dictionary["item-1"]; // throws KeyNotFoundException
var itemEmpty = dictionary["item-9"]; // throws KeyNotFoundException
StringDictionary stringDictionary = new StringDictionary();
stringDictionary.Add("ITEM-1", "VALUE-1");
var item1String = stringDictionary["item-1"]; //return "VALUE-1"
var itemEmptystring = stringDictionary["item-9"]; //return null
bool isKey = stringDictionary.ContainsValue("VALUE-1"); //return true
bool isValue = stringDictionary.ContainsValue("value-1"); //return false
System.Collections.Generic.Dictionary
不能在应用程序设置 (Properties.Settings
) 中使用,而 System.Collections.Specialized.StringDictionary
可以。
Dictionary<string,string>
(除非你需要针对1.1版本)。 - Mehrdad AfshariStringDictionary
的速度,结果表现得比较差(虽然这些大多数情况下并不重要)。说实话,我之前一直以为StringDictionary
是一种专门用于加速以string
作为键的集合类型,但是在我的测试中它表现得比较差,于是我上网搜索了一下,才发现它是非泛型的。 - nawfal