Files
freeCodeCamp/guide/chinese/csharp/null-coalescing-operator/index.md
Randell Dawson 0a1eeea424 fix(guide) Replace invalid prism code block names (#35961)
* fix: replace sh with shell

fix replace terminal with shell

fix replace node with js

fix replace output with shell

fix replace cs with csharp

fix replace c++ with cpp

fix replace c# with csharp

fix replace javasctipt with js

fix replace syntax  with js

fix replace unix with shell

fix replace linux with shell

fix replace java 8 with java

fix replace swift4 with swift

fix replace react.js with jsx

fix replace javascriot with js

fix replace javacsript with js

fix replace c++ -  with cpp

fix: corrected various typos

fix: replace Algorithm with nothing

fix: replace xaml with xml

fix: replace solidity with nothing

fix: replace c++ with cpp

fix: replace txt with shell

fix: replace code with json and css

fix: replace console with shell
2019-05-15 19:08:19 +02:00

1.6 KiB
Raw Blame History

title, localeTitle
title localeTitle
Null-coalescing Operator 空结合运算符

空结合运算符

C中的null-coalescing运算符用于帮助将一个变量分配给另一个变量如果源值为null ,则指定备用值。 C中的null-coalescing运算符是??

例1

由于namenull clientName将为clientName分配值“John Doe”。

string name = null; 
 
 string clientName = name ?? "John Doe"; 
 
 Console.WriteLine(clientName); 
> John Doe 

例2

由于name不为null clientName将为clientName分配name的值即“Jane Smith”。

string name = "Jane Smith"; 
 
 string clientName = name ?? "John Doe"; 
 
 Console.WriteLine(clientName); 
> Jane Smith 

替代if ... else语句

您可以使用if...else语句来测试是否存在null并分配不同的值。

string clientName; 
 
 if (name != null) 
    clientName = name; 
 else 
    clientName = "John Doe"; 

但是使用null-coalescing运算符可以大大简化这一点。

string clientName = name ?? "John Doe"; 

条件(三元)运算符的替代

也可以使用条件运算符来测试null的存在并分配不同的值。

string clientName = name != null ? name : "John Doe"; 

同样这可以使用null-coalescing运算符进行简化。

string clientName = name ?? "John Doe"; 

参考