c#避免变量声明

fre*_*hie 12 c#

假设我有一些像这样的代码:

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使用给定参数调用的结果" - 此时,单行版本实现了该描述.

  • @frenchie:很难给出与您给出的示例完全不同的代码建议.我还建议,如果你发现你的局部变量难以跟踪,你的方法可能比它们应该更长.您不应该使用前缀来理解您的代码. (10认同)
  • @frenchie:你在寻找`variable = condition?SomeMethod():String.Empty`? (3认同)

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)

我认为最后一个版本具有高可读性和易于调试.

  • @frenchie:你可以在else块中使用`theString = null`.在大多数情况下,您可以重构代码以避免在设置实际值之前将变量临时初始化为null,但是您必须在我对其进行评论之前发布您的特定代码. (2认同)