1

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

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

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

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

我可以处理这种情况的最佳方法是什么?UserDefined在使用 TryGetValue 之前是否必须检查是否为空?因为如果我不得不使用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;
}
4

2 回答 2

5

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

var dictionary = watsonResponse.Context.Skills[MAIN_SKILL].UserDefined;
if (dictionary?.TryGetValue("action", out var actionObj)??false)
{
    var actionName = (string)actionObj;
}
于 2022-01-06T19:52:12.530 回答
1

另一种选择是与 比较true

它看起来有点奇怪,但它适用于三值逻辑,并说:is this value truebut not false ornull

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

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

if (watsonResponse.Context.Skills[MAIN_SKILL]
    .UserDefined?.TryGetValue("action", out var actionObj) != true)
{
    var actionName = (string)actionObj;
}
于 2022-01-06T22:06:56.153 回答