我正试图像往常一样在字典上使用TryGetValue,如下所示:
Response.Context.Skills[MAIN_SKILL].UserDefined.TryGetValue("action", out var actionObj)我的问题是字典本身可能是空。我可以简单地用“?”在UserDefined之前,但随后我会收到错误:
"cannot implicitly convert type 'bool?' to 'bool'"我能处理这种情况的最好方法是什么?在使用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;
}发布于 2022-01-06 19:52:12
在??表达式之后添加空检查( bool?操作符):
var dictionary = watsonResponse.Context.Skills[MAIN_SKILL].UserDefined;
if (dictionary?.TryGetValue("action", out var actionObj)??false)
{
var actionName = (string)actionObj;
}发布于 2022-01-06 22:06:56
另一种选择是与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://stackoverflow.com/questions/70612752
复制相似问题