我想像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;
}
uj5u.com熱心網友回復:
??在bool?運算式后添加一個空檢查(運算子):
var dictionary = watsonResponse.Context.Skills[MAIN_SKILL].UserDefined;
if (dictionary?.TryGetValue("action", out var actionObj)??false)
{
var actionName = (string)actionObj;
}
uj5u.com熱心網友回復:
另一種選擇是與true.
它看起來有點奇怪,但它適用于三值邏輯并說:是這個值true但不是 false或null
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404552.html
標籤:
上一篇:Python-基于字典用其他字符替換字串串列中的多個字符
下一篇:將字典中的值拆分為片段并生成新值
