.net:添加字典项 - 检查是否存在或允许异常? [英] .net: Adding dictionary item - check if it exists or allow exception?

查看:183
本文介绍了.net:添加字典项 - 检查是否存在或允许异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向StringDictionary添加项目,可能会出现重复的键。这将会引起例外。



如果重复的机会非常低(即很少会发生),我最好使用Try Catch块并离开或者我应该在添加每个条目之前先做一个.ContainsKey检查?



我假设如果重复键的可能性很高,那么允许异常作为一个不好的决定,因为它们是昂贵的。



想法?



修改 / p>

我在通用词典中使用反射器,发现以下内容为ContainsKey和TryGetValue,如下所述。

  public bool TryGetValue(TKey key,out TValue value)
{
int index = this.FindEntry(key);
if(index> = 0)
{
value = this.entries [index] .value;
返回true;
}
value = default(TValue);
返回false;
}

And

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

我缺少一些东西,还是TryGetValue比ContainsKey做更多的工作? p>




我感谢回复,为了目前的目的,我要做一个ContainsKey调用,因为集合将小,代码更可读。

解决方案

如何解决这个问题取决于您如何发生碰撞时要做什么。如果要保留第一个插入值,则应在插入之前使用 ContainsKey 进行检查。另一方面,如果要使用该密钥的最后一个值,可以这样做:

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

作为附注:如果可能,我可能会使用 Dictionary< string,string> 而不是 StringDictionary 。如果没有什么可以让您访问更多的Linq扩展方法。


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.

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.

Thoughts?

Edit

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

And

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

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


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.

解决方案

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;

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.

这篇关于.net:添加字典项 - 检查是否存在或允许异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆