你如何检查 if 语句中的可空值

How do you check for nullable value in an if statement

我有以下代码:

string thing="";
if(request.Session.Attributes?.TryGetValue("varName", out thing))
{
  //do stuff
}

request.Session.Attributes 是字典。

我知道你不能if(bool?),这就是上面的内容。 我也知道您 可以 有 .GetValueOrDefault() 以便 null 将被视为 false。 但是我做不到request.Session.Attributes?.GetValueOrDefault().TryGetValue("varName", out thing) 那么,如果属性是 null,那么 return false 的正确方法是什么,否则 return 来自 TryGetValue 的 bool

我怀疑您正在寻找:

if (request.Session.Attributes?.TryGetValue("varName", out thing) == true)

或者:

if (request.Session.Attributes?.TryGetValue("varName", out thing) ?? false)

此处的空合并 ?? 运算符实际上是在说“如果我们没有调用 TryGetValue 因为 Attributes 为空,这就是我想假装它返回的内容。 “

一种快速但有点脏的方法是:

string thing="";
if(request.Session.Attributes?.TryGetValue("varName", out thing) ?? false)
{
  //do stuff
}

通过这种方式,您可以确定如果 Attributes 为 null,将选择 ?? 的第二个分支并且它不会进入 if.

就我个人而言,我会拆分它,因为将它放在 1-liner 中不会对代码有太大改进。它会变成:

string thing="";
var attributes = request.Session.Attributes; 
if(attributes != null && attributes.TryGetValue("varName", out thing))
{
  //do stuff
}

这更具可读性。有时,如果不改进代码,避免使用语言的新功能是公平的。

额外提示: 您可以获得一行,删除 things 的声明并将其放在 out 之后: attributes.TryGetValue("varName", out string thing)

要在 c# 中设置可空类型的默认值,您可以使用 ??运算符

if(nullableboolean ?? false){
}

所以默认为 false

像这样:

Dictionary<string,string> stuff = null;
if(stuff?.TryGetValue("key",out string val) ?? false){
        
   Console.WriteLine("hey");
        
}