在属性中使用开关检索值时,我应该使用变量作为switch语句还是return语句?

Bob*_*ob. 0 c# coding-style switch-statement

我应该在返回之前保存switch语句的结果吗?或者,当我得到它时,我应该在开关中返回值吗?有没有一种方式比另一种更好的风格?

使用临时变量:

      public double xMax {
      get {
           double val = 0.00f;
           switch(x_option) {
                case 0:
                     val = priMax;
                     break;
                case 1:
                     val = rfMax;
                     break;
                case 2:
                     val = pwMax;
                     break;
           }

           return val;
      }
 }
Run Code Online (Sandbox Code Playgroud)

使用return语句:

 public double xMax {
      get {
           double val = 0.00f;
           switch(x_option) {
                case 0:
                     return priMax;
                case 1:
                     return rfMax;
                case 2:
                     return pwMax;
           }
      }
 }
Run Code Online (Sandbox Code Playgroud)

是否有性能差异和/或清理?

Jon*_*eet 5

我个人更喜欢第二种形式.它立即清楚地表明,一旦你得到了返回声明,你就完成了.使用额外的变量版本,您必须查看其余代码以查看是否还会发生其他任何事情.

围绕一个点返回的用C很有意义的教条,在那里你要确保你做了所有的人工清理等-但你必须考虑例外情况的可能性世界反正,和垃圾收集器处理大部分清理工作,try/finally处理剩下的工作,我发现很多情况下坚持单个出口点会使代码难以阅读 - 特别是在可以在方法开始时确定结果的情况下(例如"如果输入字符串为空,结果总是为0 - 所以只需将其返回).

编辑:只是要明确,在你的情况下,我不认为它有太大的区别.但这是一种单点返回变得混乱的代码:

 public int DoSomething(string input1, string input2)
 {
     // First simple case
     if (input1 == null || input2 == null)
     {
         return -1;
     }

     // Second simple case
     int totalLength = input1.Length + input2.Length;
     if (totalLength < 10)
     {
         return totalLength;
     }

     // Imagine lots of lines here, using input1, input2 and totalLength
     // ...
     return someComplicatedResult;
 }
Run Code Online (Sandbox Code Playgroud)

只需一个回报点,就会变成:

 public int DoSomething(string input1, string input2)
 {
     int ret;

     // First simple case
     if (input1 == null || input2 == null)
     {

         ret = -1;
     }
     else
     {
         // Second simple case
         int totalLength = input1.Length + input2.Length;
         if (totalLength < 10)
         {
             ret = totalLength;
         }
         else
         {
             // Imagine lots of lines here, using input1, input2 and totalLength
             // ...
             ret = someComplicatedResult;
         }
     }
     return ret;
 }
Run Code Online (Sandbox Code Playgroud)

绝对宁愿阅读第一种形式而不是第二种形式:

  • 更多嵌套通常会使代码更难理解.很难记住你到达的地方
  • 在第一种形式中,您可以清楚地告诉 - 如果您不再阅读任何代码 - 如果您了解基本情况,那么您已经完成了.复杂的代码之后不会有任何副作用; 我们只是要回来了.在第二个代码中,您必须在心理上跳过"其他"块以找出正在发生的事情.你正在寻找更多的代码来解决这条路.