Methods of simplifying ugly nested if-else trees in C#

前端 未结 11 673
野性不改
野性不改 2021-02-02 04:23

Sometimes I\'m writing ugly if-else statements in C# 3.5; I\'m aware of some different approaches to simplifying that with table-driven development, class hierarchy, anonimous m

11条回答
  •  醉梦人生
    2021-02-02 04:49

    I was told years ago by an instructor that 3 is a magic number. And as he applied it it-else statements he suggested that if I needed more that 3 if's then I should probably use a case statement instead.

       switch (testValue)
       {
          case = 1:
             // do something
             break;
          case = 2:
             // do something else
             break;
          case = 3:
             // do something more
             break;
          case = 4
             // do what?
             break;
          default:
             throw new Exception("I didn't do anything");
       }
    

    If you're nesting if statements more than 3 deep then you should probably take that as a sign that there is a better way. Probably like Avirdlg suggested, separating the nested if statements into 1 or more methods. If you feel you are absolutely stuck with multiple if-else statements then I would wrap all the if-else statements into a single method so it didn't ugly up other code.

提交回复
热议问题