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)
是否有性能差异和/或清理?
我个人更喜欢第二种形式.它立即清楚地表明,一旦你得到了返回声明,你就完成了.使用额外的变量版本,您必须查看其余代码以查看是否还会发生其他任何事情.
围绕一个点返回的用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)
我绝对宁愿阅读第一种形式而不是第二种形式:
| 归档时间: |
|
| 查看次数: |
155 次 |
| 最近记录: |