【发布时间】: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