代码之家  ›  专栏  ›  技术社区  ›  mattmc3

如何在没有返回变量的情况下调试VB.NET计算函数返回

  •  4
  • mattmc3  · 技术社区  · 14 年前

    Public Shared Function GetAge(ByVal dob As DateTime, ByVal asOfDate As DateTime) As Integer
       If asOfDate.Date < dob.Date Then Return 0
       Dim factor = If(asOfDate.DayOfYear < dob.DayOfYear, 1, 0)
       ' What's going to be returned?
       Return asOfDate.Year - dob.Year - factor ' Imagine that this could be a more complicated calc, or one with side-effects that would prevent me from running it in the immediate window
    End Function
    

    我发现自己改变了编写代码的方式,只是为了使调试更容易。所以这个方法会变成:

    Public Shared Function GetAge(ByVal dob As DateTime, ByVal asOfDate As DateTime) As Integer
       If asOfDate.Date < dob.Date Then Return 0
       Dim factor = If(asOfDate.DayOfYear < dob.DayOfYear, 1, 0)
       Dim result = asOfDate.Year - dob.Year - factor ' I made this variable just for setting a debugging breakpoint
       Return result ' I can now set a breakpoint here, but it seems awkward
    End Function
    

    我在调试器中是否遗漏了一些东西,可以让我更容易地看到一个方法将返回什么,而不是总是生成一个 result 变量或跳回来电,看看有什么出来?仅仅为了简化一个简单的调试任务而改变代码的编写方式似乎有点尴尬——感觉好像我遗漏了什么。

    3 回复  |  直到 14 年前
        1
  •  4
  •   GSerg    14 年前

    您可以在 End Function 行并将光标悬停在函数名上。

        2
  •  1
  •   Hans Passant    14 年前

    是的,很尴尬。visualstudio6可以做到这一点,但在以后的版本中就没有了。实现起来并不容易,托管代码如何返回值是JIT编译器的一个实现细节。对于简单的返回值类型(如Integer或objects),这一点很明显,但当方法返回结构或小数点时,它会变得复杂。

    首先将它存储在变量中并没有什么问题,JIT优化器在大多数情况下都会去掉这个变量。但是是的,它在源代码中看起来很有趣。

    不太好,但有点困难的时候可以过得去。

        3
  •  0
  •   Enigmativity    14 年前

    我倾向于更进一步,去掉 Return 0

    Public Shared Function GetAge(ByVal dob As DateTime, ByVal asOfDate As DateTime) As Integer
       Dim result = 0
       If asOfDate.Date >= dob.Date Then
          Dim factor = If(asOfDate.DayOfYear < dob.DayOfYear, 1, 0)
          result = asOfDate.Year - dob.Year - factor
       End If
       Return result
    End Function