假设我有一些像这样的代码:
public string SomeMethod(int Parameter)
{
string TheString = "";
TheString = SomeOtherMethod(Parameter);
return TheString;
}
Run Code Online (Sandbox Code Playgroud)
当然,这段代码相当于:
public string SomeMethod(int Parameter)
{
return SomeOtherMethod(Parameter);
}
Run Code Online (Sandbox Code Playgroud)
我认为第一个版本更具可读性,这就是我编写代码的方式,即使我知道我可以避免使用变量.我的问题是:编译器是否以相同的方式编译代码(即相同的性能),或者第二种选择在性能方面确实更好.
谢谢.
Jon*_*eet 20
我会说第一个表单不太可读,它包含一个冗余初始化程序.为什么要将变量初始化为"",如果你要给它一个不同的值?至少将其更改为:
public string SomeMethod(int parameter)
{
string returnValue = SomeOtherMethod(parameter);
return returnValue;
}
Run Code Online (Sandbox Code Playgroud)
或者如果你真的想要将声明与初始化分开:
public string SomeMethod(int parameter)
{
string returnValue;
returnValue = SomeOtherMethod(parameter);
return returnValue;
}
Run Code Online (Sandbox Code Playgroud)
(请注意,我还调整了命名遵循.NET命名约定并为局部变量赋予更有意义的名称 - "TheString"没有传达任何有用的含义.)
你真的不会看到使用局部变量的任何性能问题,但我真的鼓励你考虑可读性.这里局部变量的目的是什么?您可能会将该方法描述为:"返回SomeOtherMethod使用给定参数调用的结果" - 此时,单行版本实现了该描述.
Mar*_*ers 13
编译器将为您的两个示例生成非常相似的代码.但稍微修改一下就是避免初始化为一个永远不会使用的空字符串.
public string SomeMethod(int Parameter)
{
string result;
result = SomeOtherMethod(Parameter);
return result;
}
Run Code Online (Sandbox Code Playgroud)
我不确定以这种方式重写代码使其更具可读性,但它确实意味着您可以添加断点并查看result方法返回之前的值.这在调试时很有用.
请注意,您可以组合第一行和第二行,仍然可以获得此好处:
public string SomeMethod(int Parameter)
{
string result = SomeOtherMethod(Parameter);
return result;
}
Run Code Online (Sandbox Code Playgroud)
我认为最后一个版本具有高可读性和易于调试.
| 归档时间: |
|
| 查看次数: |
989 次 |
| 最近记录: |