我正在向StringDictionary添加项目,并且可能会出现重复的密钥.这当然会抛出异常.
如果重复的可能性非常低(即很少发生),我最好使用Try Catch块并使其处理不当,或者在添加每个条目之前是否应该总是进行.ContainsKey检查?
我假设如果重复密钥的可能性很高,那么允许异常将是一个糟糕的决定,因为它们很昂贵.
思考?
编辑
我在泛型字典中使用了反射器,并为ContainsKey和TryGetValue找到了以下内容,因为两者都在下面提到.
public bool TryGetValue(TKey key, out TValue value)
{
int index = this.FindEntry(key);
if (index >= 0)
{
value = this.entries[index].value;
return true;
}
value = default(TValue);
return false;
}
Run Code Online (Sandbox Code Playgroud)
和
public bool ContainsKey(TKey key)
{
return (this.FindEntry(key) >= 0);
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么,或者TryGetValue比ContainsKey做更多的工作?
我很欣赏这些回复,对于我目前的目的,我将继续做一个ContainsKey调用,因为集合很小,而且代码更具可读性.