gpt4 book ai didi

c# - 词典存储和检索

转载 作者:行者123 更新时间:2023-11-30 20:35:47 25 4
gpt4 key购买 nike

public static Dictionary<string,string> qData = new Dictionary<string,string>();
protected void Page_LoadComplete(object sender, EventArgs e)
{
qData.Add("businessName",Request.QueryString["businessName"]);
}
protected void craCHeck(object sender, EventArgs e)
{
string value = "";
value = qData["businessName"];
}

如果我不注释 qData.Add 行,它表示 key 已经添加。如果我对它发表评论,它会说找不到 key ……非常困惑和沮丧,不知道我做错了什么。 :/

最佳答案

您需要检查字典中是否已经存在键:

if(qData.ContainsKey("businessName")) 
qData["businessName"] = Request.QueryString["businessName"];
else
qData.Add("businessName", Request.QueryString["businessName"]);

Add 方法不会添加或更新键值对,但它只是添加它。否则,如果 key 已经存在于给定的字典,你需要使用上面代码中所示的索引器样本。

甚至比这更好。检查什么MSDN states关于通用字典索引器:

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.

因此,您还可以按如下方式简化代码:

// No need of using Add() or the indexer. You can 
// just use the indexer instead in either case:
qData["businessName"] = Request.QueryString["businessName"];

关于c# - 词典存储和检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37596431/

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