Ale*_*iva 1 .net c# dictionary trygetvalue
我尝试TryGetValue像往常一样在字典上使用,如下代码:
Response.Context.Skills[MAIN_SKILL].UserDefined.TryGetValue("action", out var actionObj)
Run Code Online (Sandbox Code Playgroud)
我的问题是字典本身可能为 null。我可以简单地使用“?”。在 UserDefined 之前,但随后我收到错误:
"cannot implicitly convert type 'bool?' to 'bool'"
Run Code Online (Sandbox Code Playgroud)
我处理这种情况的最佳方法是什么?UserDefined在使用 TryGetValue 之前是否必须检查是否为 null?因为如果我必须使用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;
}
Run Code Online (Sandbox Code Playgroud)
在表达式后面添加空检查(??运算符)bool?:
var dictionary = watsonResponse.Context.Skills[MAIN_SKILL].UserDefined;
if (dictionary?.TryGetValue("action", out var actionObj)??false)
{
var actionName = (string)actionObj;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1667 次 |
| 最近记录: |