1

返回 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

显然我在两个不同的级别上有一个重复的块。是否可以优化此代码以将它们拆分为一个?或类似的东西..

4

4 回答 4

11

那段代码几乎是不可读的。不要为了三元运算符而使用三元运算符;它通过消除非常简单的表达式的块来使thigs更具可读性。if你所拥有的不是。

于 2010-04-27T18:53:11.427 回答
6

您可以将表达式简化为:

if (any && !specified)
{
    return empty;
}
else
{
    return isClient ? textbox : dropdown;
}
于 2010-04-27T18:53:03.553 回答
5
any && !specified ? 
   empty : 
   isClient ? textbox : dropdown;  
于 2010-04-27T18:55:09.380 回答
0

isClient ? textbox : dropdown块放入方法中并从原始分支进行方法调用 = 不再重复代码。

于 2010-04-27T18:53:15.970 回答