嵌套三元运算符 [英] Nested ternary operators
本文介绍了嵌套三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
_viewModel.PhoneDefault = user == null ? "" :
(string.IsNullOrEmpty(user.PhoneDay) ?
(string.IsNullOrEmpty(user.PhoneEvening) ?
(string.IsNullOrEmpty(user.Mobile) ? "" :
user.Mobile) :
user.PhoneEvening) :
user.PhoneDay);
是否有更好的方式编写此代码以使其更具可读性?
Is there a better way to write this to make it more readable?
推荐答案
在您的情况下,您可以编写一个辅助函数,如下所示:
In your case you can write a helper function, like this:
// return the first parameter that isn't null or empty
public static string CoalesceStrings(params string[] src)
{
foreach (var str in src)
if (!string.IsNullOrEmpty(str))
return str;
return "";
}
然后只需调用它,就像这样:
Then just call it, like this:
_viewModel.PhoneDefault = user == null ? "" :
CoalesceStrings(user.PhoneDay, user.PhoneEvening, user.Mobile);
这篇关于嵌套三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文