gpt4 book ai didi

c# - 是否有更优雅的方式将项目安全地添加到 Dictionary<> 中?

转载 作者:IT王子 更新时间:2023-10-29 03:33:24 27 4
gpt4 key购买 nike

我需要将键/对象对添加到字典中,但我当然需要先检查键是否已经存在,否则我会收到“键已存在于字典中”错误。下面的代码解决了这个问题,但是很笨重。

在不创建像这样的字符串辅助方法的情况下,有什么更优雅的方法可以做到这一点?

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

最佳答案

只需使用索引器 - 如果它已经存在,它将被覆盖,但它并不必须首先存在:

Dictionary<string, object> currentViews = new Dictionary<string, object>();
currentViews["Customers"] = "view1";
currentViews["Customers"] = "view2";
currentViews["Employees"] = "view1";
currentViews["Reports"] = "view1";

如果键的存在表明存在错误(因此您希望它抛出),则基本上使用 Add,否则使用索引器。 (这有点像转换和使用 as 进行引用转换的区别。)

如果您使用的是 C# 3 并且您有一组不同的键,您可以使它更整洁:

var currentViews = new Dictionary<string, object>()
{
{ "Customers", "view2" },
{ "Employees", "view1" },
{ "Reports", "view1" },
};

但这在您的情况下不起作用,因为集合初始值设定项始终使用 Add,这将引发第二个 Customers 条目。

关于c# - 是否有更优雅的方式将项目安全地添加到 Dictionary<> 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1177517/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com