如何在C#中设置变量的默认值?
我想设置一个变量为默认值,如果分配返回null或其他。如何在C#中设置变量的默认值?
string a = GetValue();
如果GetValue返回null,那么我想有一个变量a的默认值,如何在c#中做到这一点。尽量不要使用if。
谢谢你的时间。
使用空合并运算符。
string a = GetValue() ?? "Default";
这个怎么样?
string a = GetValue() != null ? GetValue() : "default";
坏主意,如果'的GetValue()'有副作用... – Arnout 2010-11-19 12:00:34
关闭,但batwad的解决方案是平滑的)。你也需要将它改为:“1”; – 2010-11-19 12:00:50
这对GetValue()进行了两次评估,并且比空聚并运算符''更加丑陋。 – CodesInChaos 2010-11-19 12:01:15
string a = GetValue()== null? string.empty:GetValue();
这是很难实现的方法,'GetValue()'可能会被调用两次。 – 2010-11-19 12:01:19
string a = GetValue() ?? "DefaultValue";
这将是
string a = GetValue() ?? "default value";
你们太快了。 – user469652 2010-11-19 12:02:00