基本用法
如果左侧操作数为 null
,则使用 null-coalescing operator (??)
允许你为可空类型指定默认值。
string testString = null;
Console.WriteLine("The specified string is - " + (testString ?? "not provided"));
这在逻辑上等同于:
string testString = null;
if (testString == null)
{
Console.WriteLine("The specified string is - not provided");
}
else
{
Console.WriteLine("The specified string is - " + testString);
}
或使用三元运算符(?:) 运算符:
string testString = null;
Console.WriteLine("The specified string is - " + (testString == null ? "not provided" : testString));