Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?
是否有一个语句或一行方式来完成这样的事情,其中字符串s被声明并且在表达式中分配了第一个非空值?
//pseudo-codeish
string s = Coalesce(string1, string2, string3);
or, more generally,
或者,更一般地说,
object obj = Coalesce(obj1, obj2, obj3, ...objx);
2 个解决方案
#1
14
As Darren Kopp said.
正如Darren Kopp所说。
Your statement
object obj = Coalesce(obj1, obj2, obj3, ...objx);
Can be written like this:
可以像这样写:
object obj = obj1 ?? obj2 ?? obj3 ?? ... objx;
to put it in other words:
换句话说:
var a = b ?? c;
is equivalent to
相当于
var a = b != null ? b : c;
#2
2
the ?? operator.
?? ??运营商。
string a = nullstring ?? "empty!";
#1
14
As Darren Kopp said.
正如Darren Kopp所说。
Your statement
object obj = Coalesce(obj1, obj2, obj3, ...objx);
Can be written like this:
可以像这样写:
object obj = obj1 ?? obj2 ?? obj3 ?? ... objx;
to put it in other words:
换句话说:
var a = b ?? c;
is equivalent to
相当于
var a = b != null ? b : c;
#2
2
the ?? operator.
?? ??运营商。
string a = nullstring ?? "empty!";