[英]Optimize conditional operators branching in C#
返回this.AllowChooseAny.Value吗? radioSpecific.Checked? UserManager.CurrentUser.IsClient吗? txtSubject.Text:subjectDropDownList.SelectedItem.Text:String.Empty:UserManager.CurrentUser.IsClient? txtSubject.Text:subjectDropDownList.SelectedItem.Text;
或更简单的形式:
return any ?
specified ?
isClient ? textbox : dropdown :
empty :
isClient ? textbox : dropdown;
或以示意图形式:
|
any
/ \
specified isClient
/ \ / \
isClient empty textbox dropdown
/ \
textbox dropdown
显然,我在两个不同级别上有一个重复的块。 有可能优化此代码以将它们拆分为一个吗? 或类似的东西..
该代码块几乎是不可读的。 不要仅仅为了三元运算符而使用三元运算符。 通过消除非常简单的表达式的if
块,可以使thig 更具可读性。 你所没有的。
您可以将表达式简化为:
if (any && !specified)
{
return empty;
}
else
{
return isClient ? textbox : dropdown;
}
any && !specified ?
empty :
isClient ? textbox : dropdown;
把isClient ? textbox : dropdown
isClient ? textbox : dropdown
方法中的isClient ? textbox : dropdown
框,并从您的原始分支进行方法调用=不再重复代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.