2010-11-19 44 views
3

我想设置一个变量为默认值,如果分配返回null或其他。如何在C#中设置变量的默认值?

string a = GetValue(); 

如果GetValue返回null,那么我想有一个变量a的默认值,如何在c#中做到这一点。尽量不要使用if。

谢谢你的时间。

回答

11

使用空合并运算符。

string a = GetValue() ?? "Default"; 
+0

你们太快了。 – user469652 2010-11-19 12:02:00

0

这个怎么样?

string a = GetValue() != null ? GetValue() : "default";

+3

坏主意,如果'的GetValue()'有副作用... – Arnout 2010-11-19 12:00:34

+0

关闭,但batwad的解决方案是平滑的)。你也需要将它改为:“1”; – 2010-11-19 12:00:50

+0

这对GetValue()进行了两次评估,并且比空聚并运算符''更加丑陋。 – CodesInChaos 2010-11-19 12:01:15

0

string a = GetValue()== null? string.empty:GetValue();

+2

这是很难实现的方法,'GetValue()'可能会被调用两次。 – 2010-11-19 12:01:19

1
string a = GetValue() ?? "DefaultValue"; 
1

这将是

string a = GetValue() ?? "default value"; 
相关问题