C# 是否有更优雅的方式将项目安全地添加到 Dictionary<> 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1177517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a more elegant way of adding an item to a Dictionary<> safely?
提问by Edward Tanguay
I need to add key/object pairs to a dictionary, but I of course need to first check if the key already exists otherwise I get a "key already exists in dictionary" error. The code below solves this but is clunky.
我需要将键/对象对添加到字典中,但我当然需要首先检查键是否已经存在,否则我会收到“字典中已存在键”错误。下面的代码解决了这个问题,但很笨重。
What is a more elegant way of doing this without making a string helper method like this?
在不制作这样的字符串辅助方法的情况下,有什么更优雅的方法可以做到这一点?
using System;
using System.Collections.Generic;
namespace TestDictStringObject
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> currentViews = new Dictionary<string, object>();
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2");
StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1");
foreach (KeyValuePair<string, object> pair in currentViews)
{
Console.WriteLine("{0} {1}", pair.Key, pair.Value);
}
Console.ReadLine();
}
}
public static class StringHelpers
{
public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, view);
}
else
{
dict[key] = view;
}
}
}
}
采纳答案by Jon Skeet
Just use the indexer - it will overwrite if it's already there, but it doesn't haveto be there first:
只需使用索引-如果它已经存在,它将覆盖,但它不具备在那里第一次:
Dictionary<string, object> currentViews = new Dictionary<string, object>();
currentViews["Customers"] = "view1";
currentViews["Customers"] = "view2";
currentViews["Employees"] = "view1";
currentViews["Reports"] = "view1";
Basically use Add
if the existence of the key indicates a bug (so you want it to throw) and the indexer otherwise. (It's a bit like the difference between casting and using as
for reference conversions.)
Add
如果键的存在表明存在错误(因此您希望它抛出),则基本上使用,否则使用索引器。(这有点像转换和as
用于参考转换之间的区别。)
If you're using C# 3 and you have a distinct set of keys, you can make this even neater:
如果您使用的是 C# 3并且您有一组不同的键,则可以将其做得更简洁:
var currentViews = new Dictionary<string, object>()
{
{ "Customers", "view2" },
{ "Employees", "view1" },
{ "Reports", "view1" },
};
That won't work in your case though, as collection initializers always use Add
which will throw on the second Customers
entry.
但是,这在您的情况下不起作用,因为集合初始值设定项始终使用Add
which 将抛出第二个Customers
条目。
回答by Mehrdad Afshari
What's wrong with...
怎么了...
dict[key] = view;
It'll automatically add the key if it's non-existent.
如果它不存在,它会自动添加密钥。
回答by Steve Gilham
simply
简单地
dict[key] = view;
From the MSDN documentation of Dictionary.Item
来自 Dictionary.Item 的 MSDN 文档
The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.
与指定键关联的值。如果未找到指定的键,则 get 操作会抛出 KeyNotFoundException ,而set 操作会创建一个具有指定键的新元素。
My emphasis
我的重点
回答by rohancragg
As usual John Skeet gets in there with lighting speed with the right answer, but interestingly you could also have written your SafeAdd as an Extension Method on IDictionary.
像往常一样,John Skeet 以闪电般的速度获得了正确的答案,但有趣的是,您也可以将 SafeAdd 编写为 IDictionary 上的扩展方法。
public static void SafeAdd(this IDictionary<K, T>. dict, K key, T value)...
回答by Daniel Earwicker
Although using the indexer is clearly the right answer for your specific problem, another more general answer to the problem of adding additional functionality to an existing type would be to define an extension method.
尽管使用索引器显然是解决您的特定问题的正确答案,但对向现有类型添加附加功能的问题的另一个更通用的答案是定义扩展方法。
Obviously this isn't a particularly useful example, but something to bear in mind for the next time you find a real need:
显然,这不是一个特别有用的例子,但下次你发现真正需要时要记住:
public static class DictionaryExtensions
{
public static void SafeAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict,
TKey key, TValue value)
{
dict[key] = value;
}
}