首页 > 解决方案 > 安全地访问和解析字典中的布尔值

问题描述

我有一个使用 aDictionary<String,String>来存储配置的应用程序。

我想要:

  1. 检查字典是否包含“Key”
  2. 将“键”的值解析为布尔值
  3. 如果未找到,则默认为 false

目前我正在做以下事情

bool settingBool = false
if (configDictionary.ContainsKey("Key")) {
   bool.Tryparse(configDictionary["Key"], out settingBool)
}
// Do some stuff with settingBool

上述方法是否存在任何缺陷或明显问题,尤其是在可读性/可维护性方面?

标签: c#

解决方案


上述方法是否存在任何缺陷或明显问题,尤其是在可读性/可维护性方面?

作为@Cetin Basoz answer的补充。


既然你想和你一起做点什么,settingsBool我个人会去configDictionary.TryGetValue("Key", out value),因为

尝试获取值

此方法结合了 ContainsKey 方法和 Item[TKey] 属性的功能。

所以对于你的例子:

var configDictionary = new Dictionary<string,string>() { { "Key" , "Value"} };

string value;
bool settingBool; 
if ( configDictionary.TryGetValue("Key", out value) 
     && bool.TryParse(value, out settingBool) )
{
    // Do something with your settingBool
}
else
{
    // Do something if "Key" is not present or Value could not be parsed.
}

提示:您不需要设置settingBoolto false,因为false它是默认值。尝试default(bool)


推荐阅读