c# 运算符:? ,??

时间:2021-09-12 03:54:23

参考微软帮助

1  ?  空值条件运算符,用于在执行成员访问 (?.) 或索引 (?[) 操作之前,测试是否存在 NULL。

 // ? 空值条件运算符
string str = null;
Console.WriteLine(str?.Length );//和下面的if语句等价,也就是先判断str是否为空值,如果为空值就不往下进行计算了,如果str不为空值,则输出str字符串的长度。
if (str !=null)
{
Console.WriteLine(str.Length);
}
Console.ReadKey();

2     ?? 运算符称作 null 合并运算符。 如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。 

 // ?? null合并运算符
string str = null;
string str2;
str2 = str ?? "www"; //和下面的if语句等价,如果str不为空,那么就将str赋给str2,否则将“www”赋给str2.
if (str != null)
{
str2 = str;
}
else
{
str2 = "www";
}