.NET:添加字典项 - 检查它是否存在,或者允许例外?是否存在、字典、NET

2023-09-04 02:08:25 作者:青池゛旧时光ㄟ

我添加项目到StringDictionary,它可能是一个重复键上来了。当然,这会抛出异常。

I'm adding items to a StringDictionary and it's possible that a duplicate key will come up. This will of course throw an exception.

如果重复的几率是非常低的(也就是说,它会很少发生),我是不是最好使用try catch块,留下它未处理的,还是应该将每个条目之前,我总是做一个.ContainsKey检查?

If the chance of duplicates is very low (ie it will rarely happen), am I better off using a Try Catch block and leaving it unhandled, or should I always do a .ContainsKey check before adding each entry?

我假设,如果重复键的可能性高,则允许的例外是一个贫穷的决定,因为他们是昂贵的。

I'm assuming that if the likelihood of duplicate keys was high, then allowing exceptions would be a poor decision as they are expensive.

思考?

修改

我用反射镜上的通用词典,发现了以下内容的containsKey和TryGetValue,因为两者都如下所述。

I used reflector on the generic Dictionary and found the following for ContainsKey and TryGetValue, as both were mentioned below.

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

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

我缺少的东西,或者是TryGetValue做更多的工作比的containsKey?

Am I missing something, or is TryGetValue doing more work than ContainsKey ?

我AP preciate的反应,我现在的目的,我会去与做的containsKey调用该集合将很小,而code更具可读性。

I appreciate the responses, and for my current purpose I'm going to go with doing a ContainsKey call as the collection will be small, and the code more readable.

推荐答案

如何处理这取决于你想要做的,如果碰撞发生的事情。如果你想保持第一插入值,你应该使用的containsKey 插入前检查。如果,另一方面,你要使用的最后的值,该键,你可以像这样:

How to approach this depends on what you want to do if a collision happens. If you want to keep the first inserted value, you should use ContainsKey to check before inserting. If, on the other hand, you want to use the last value for that key, you can do like so:

// c# sample:
myDictionary[key] = value;

作为一个方面说明:我可能会,如果可能的话,使用词典<字符串,字符串> 而不是 StringDictionary 。如果不出意外,这将让你获得更多的LINQ扩展方法。

As a side note: I would probably, if possible, use Dictionary<string, string> instead of StringDictionary. If nothing else that will give you access to some more Linq extension methods.

 
精彩推荐
图片推荐