[英]How to set default value for a variable in C#?
I want to set a variable to a default value if the assignment returns null or something else. 如果赋值返回null或其他内容,我想将变量设置为默认值。
string a = GetValue();
if GetValue returns null, then I want to have a default value for variable a, how to do that in c#. 如果GetValue返回null,那么我想为变量a设置一个默认值,如何在c#中执行此操作。 Try not using if.
尽量不要使用if。
Thanks for the time. 谢谢你的时间。
使用null合并运算符。
string a = GetValue() ?? "Default";
string a = GetValue() ?? "DefaultValue";
那将是
string a = GetValue() ?? "default value";
这个怎么样?
string a = GetValue() != null ? GetValue() : "default";
string a = GetValue() == null ? string a = GetValue()== null? string.empty : GetValue();
string.empty:GetValue();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.