【问题标题】:TryGetValue on a null dictionary空字典上的 TryGetValue
【发布时间】:2022-01-06 19:39:25
【问题描述】:

我正在尝试像往常一样在字典上使用TryGetValue,如下面的代码:

Response.Context.Skills[MAIN_SKILL].UserDefined.TryGetValue("action", out var actionObj)

我的问题是字典本身可能为空。我可以简单地使用“?”。在 UserDefined 之前,但随后我收到错误:

"cannot implicitly convert type 'bool?' to 'bool'"

处理这种情况的最佳方法是什么?在使用 TryGetValue 之前是否必须检查 UserDefined 是否为空?因为如果我必须使用 Response.Context.Skills[MAIN_SKILL].UserDefined 两次,我的代码可能看起来有点乱:

if (watsonResponse.Context.Skills[MAIN_SKILL].UserDefined != null && 
    watsonResponse.Context.Skills[MAIN_SKILL].UserDefined.TryGetValue("action", out var actionObj))
{
    var actionName = (string)actionObj;
}

【问题讨论】:

  • 为那个冗长的词使用一个变量。
  • 在拨打电话前检查 null。这样您就不必使用 TryGetvalue。
  • @SmithaKalluz:这些完全不相关。

标签: c# .net dictionary trygetvalue


【解决方案1】:

bool? 表达式之后添加一个空检查(?? 运算符):

var dictionary = watsonResponse.Context.Skills[MAIN_SKILL].UserDefined;
if (dictionary?.TryGetValue("action", out var actionObj)??false)
{
    var actionName = (string)actionObj;
}

【讨论】:

  • 谢谢!这实际上解决了我的问题。但是我仍然收到 Use of unassigned local variable 'actionObj'... 是我在 if 语句之前声明该对象的唯一选择吗?
  • @AlexandrePaiva 是的,你必须这样做。如果你考虑一下逻辑,你就会明白为什么会抛出这个错误
  • @Charlieface 是的,我会在那之前声明这个对象。仅作为功能参考,我发现了一个关于 TryGetValue 中使用局部变量的有趣讨论的问题:stackoverflow.com/questions/56779825/…
【解决方案2】:

另一种选择是与true 进行比较。

看起来有点奇怪,但它适用于三值逻辑并说:这个值是true不是 falsenull

if (watsonResponse.Context.Skills[MAIN_SKILL]
    .UserDefined?.TryGetValue("action", out var actionObj) == true)
{
    var actionName = (string)actionObj;
}

你可以用!= true做相反的逻辑:这个值不是true,所以要么false要么null

if (watsonResponse.Context.Skills[MAIN_SKILL]
    .UserDefined?.TryGetValue("action", out var actionObj) != true)
{
    var actionName = (string)actionObj;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 2023-03-05
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多