c#中的问号点操作符含义

Console.WriteLine(
$"3. Endpoint: {context.GetEndpoint()?.DisplayName ?? "(null)"}");

以上代码等同于下面的代码

string info = string.empty;
if(context.GetEndpoint()==null)
{
info = "(null)";
}
else if(context.GetEndpoint().DisplayName ==null)
{
info = "null";
}
else
{
info = context.GetEndpoint().DisplayName;
}
Console.WriteLine($"3. Endpoint:{info}“):

It’s the null conditional operator. It basically means:

“Evaluate the first operand; if that’s null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand).”

如果问号前面的是null,则该表达式直接返回null,
如果不为空,则继续进行下一步,通过点语法糖获取属性。

双问号的意思是如果是空,则返回后面的信息,否则返回自身结果。

你可能感兴趣的:(C#)