简体   繁体   English

优化C#中的条件运算符分支

[英]Optimize conditional operators branching in C#

return this.AllowChooseAny.Value ? 返回this.AllowChooseAny.Value吗? radioSpecific.Checked ? radioSpecific.Checked? UserManager.CurrentUser.IsClient ? UserManager.CurrentUser.IsClient吗? txtSubject.Text : subjectDropDownList.SelectedItem.Text : String.Empty : UserManager.CurrentUser.IsClient ? txtSubject.Text:subjectDropDownList.SelectedItem.Text:String.Empty:UserManager.CurrentUser.IsClient? txtSubject.Text : subjectDropDownList.SelectedItem.Text; txtSubject.Text:subjectDropDownList.SelectedItem.Text;

or in less complex form: 或更简单的形式:

return any ?
    specified ?
       isClient ? textbox : dropdown :
       empty :
    isClient ? textbox : dropdown;

or in schematic form: 或以示意图形式:

                     |
                    any
              /            \
      specified             isClient
      /        \           /        \
  isClient    empty     textbox  dropdown
  /       \
textbox  dropdown

Evidently I have a duplicated block on two different levels. 显然,我在两个不同级别上有一个重复的块。 Is it possible to optimize this code to probably split them to one? 有可能优化此代码以将它们拆分为一个吗? Or something like that.. 或类似的东西..

That block of code is nearly unreadable. 该代码块几乎是不可读的。 Don't use the ternary operator just for the sake of the ternary operator; 不要仅仅为了三元运算符而使用三元运算符。 it's there to make thigs more readable by eliminating if blocks for very simple expressions. 通过消除非常简单的表达式的if块,可以使thig 更具可读性。 What you have is not. 你所没有的。

You can simplify your expression to this: 您可以将表达式简化为:

if (any && !specified)
{
    return empty;
}
else
{
    return isClient ? textbox : dropdown;
}
any && !specified ? 
   empty : 
   isClient ? textbox : dropdown;  

Put the isClient ? textbox : dropdown isClient ? textbox : dropdown isClient ? textbox : dropdown block in a method and make method calls from you original branch = no more code duplication. isClient ? textbox : dropdown方法中的isClient ? textbox : dropdown框,并从您的原始分支进行方法调用=不再重复代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM