c# - 如何避免字典中的空键错误?

标签 c# static-methods

如果键为空,如何避免错误?

//Getter/setter
public static Dictionary<string, string> Dictionary
{
    get { return Global.dictionary; }
    set { Global.dictionary = value; }
}

更新:

Dictionary.Add("Key1", "Text1");
Dictionary["Key2"] <-error! so what can I write in the GET to avoid error?

谢谢。

问候

最佳答案

使用TryGetValue:

Dictionary<int, string> dict = ...;
string value;

if (dict.TryGetValue(key, out value))
{
    // value found
    return value;
}
else
{
    // value not found, return what you want
}

关于c# - 如何避免字典中的空键错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4085983/

相关文章:

c# - 使用 lambda ID(distinct) 和特定 ID 的计数从列表中返回 2 个属性?

c# - 如何从 MS Word 访问表格中具有不同单元格宽度的列

c# - 关于泛型、继承和链接的棘手问题

java - 读取方法中返回的ArrayList - java

php - 为什么在 PHP 的 laravel 模型类中使用静态方法?

java - 使用 JSONObject Java 类的静态 getNames 方法时,Eclipse 中出现语法错误

c# - 无法读取配置部分 'customErrors',因为它缺少部分声明

c# - Windows 10 中的 WiFi Direct 显示 "UnsupportedHardware",尽管它应该受支持

java - 将示例 java 代码转换为 ruby​​ 以了解 ruby​​ 中的静态变量

java - 将静态 java 对象用于软件组件