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

本文关键字:is 变量 int 方式更 返回 | 更新日期: 2023-09-27 18:20:47

我仍然在学习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将所有内容都视为int,所以我看不到任何类型的问题。我很想听听专家们对C#中哪种方式最合适的反馈。

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

Q:有区别吗?

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


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

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


问:这真的会在运行时间、结果、准确性等方面产生影响吗。?

A:一点也不。


未来意见

Q:我应该使用哪一个作为"如何做事"的模板?

A:对于这类代码,第一个。如果你在阅读代码时遇到问题,比如有很多移动部分和子表达式的大表达式,可以随意创建具有良好名称的新变量,记录这些子表达式是什么、做什么和计算,但不要因为可以而只引入变量。

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

很少有建议:

  1. 尽量避免嵌套if语句(if在if内部)。有时这并不像听起来那么容易,但视觉工作室有一些复杂度的测量方法可以帮助你。

    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;
    }