返回int的方法更合适,即需要变量

时间:2015-11-06 12:58:29

标签: c#

我还在学习C#,从VB.Net迁移过来,我总是想知道,在某些情况下,为什么我需要一个变量。

鉴于此片段;

public int GetWaitTime(bool webProtocolError, int currentWait)
    {
       if (!webProtocolError)
        {
            if (currentWait < 16000)
                return currentWait + 250;
        }

        if (currentWait < 10000)
        {
            return 10000;
        }
        if (currentWait < 240000 && currentWait >=10000)
        {
            return currentWait*2;
        }
        return 240000;
    }

与此片段相对照

public int GetWaitTime(bool webProtocolError, int currentWait)
    {
       var newWait = currentWait;
       if (!webProtocolError)
        {
            if (currentWait < 16000)
                newWait = currentWait + 250;
                return newWait;
        }
        if (currentWait < 10000)
        {
            newWait =10000;
            return newWait;
        }
        if (currentWait < 240000 && currentWait >=10000)
        {
            newWait = currentWait*2;
            return newWait;
        }
        return 240000;
  }

有什么真正的区别吗? Visual Studio将所有内容视为整体,因此我没有看到任何类型问题。我很乐意听取专家对C#中最合适的反馈意见。

2 个答案:

答案 0 :(得分:4)

问:有区别吗?

答:是的,您已在第二个示例中声明了一个额外的变量。

问:这会对最终编译的代码产生影响吗?

A:可能会也可能不会。例如,编译器可能决定在第一个代码片段中创建一个临时的未命名变量,这将使两个实际编译成几乎相同的IL。

问:这实际上会在运行时,结果,准确度等方面产生影响吗?

A:没有丝毫。

提前意见

问:我应该将哪一个用作“如何做事”的模板?

答:对于这种代码,第一种。如果您在阅读代码时遇到问题,例如具有大量移动部件和子表达式的大表达式,请随意创建具有良好名称的新变量,以记录这些子表达式的内容,执行和计算,但不要只是引入变量,因为您可以

答案 1 :(得分:0)

没有真正的区别,这里的主要是代码风格。它应该易于遵循和维护。

很少有人推荐:

  1. 尝试避免使用嵌套的if语句(如果在if中)。有时它并不像听起来那么容易,但是visual studio已经complexity measures来帮助你了。

    if (!webProtocolError)
    {
        if (currentWait < 16000)
           return currentWait + 250;
    }
    
    if (!webProtocolError && currentWait < 16000)
    {
        return currentWait + 250;
    }
    
  2. 请尝试避免使用幻数(如果适用)。使用班上描述的常量。

    if (currentWait < 10000)
    {
        newWait =10000;
        return newWait;
    }
    
    private const int MinimumWait= 10000;
    if (currentWait < MinimumWait)
    {
        return MinimumWait;
    }
    
  3. 如果您希望存储函数的结果,请在体内进行调用并在方法结束时使用它返回。

    public int GetWaitTime(bool webProtocolError, int currentWait)
    {
        var newWait = 240000;
        if (!webProtocolError)
        {
            if (currentWait < 16000)
                newWait = currentWait + 250;
        }
        if (currentWait < 10000)
        {
            newWait = 10000;
        }
        if (currentWait < 240000 && currentWait >=10000)
        {
            newWait = currentWait * 2;
        }
    
        return newWait;
    }