0

我有这段 VB.net 代码,我试图弄清楚为什么它是合法的:

Class Program
    Public Shared Sub Main(args As String())

        Console.WriteLine(New wtf().TestCrazyAssignment())
        Console.ReadKey()

    End Sub

    Class wtf
        Public recurse As int32 = 0
        Public Function TestCrazyAssignment() As string
            TestCrazyAssignment = "this should not be possible."

            'BadAllocation = "something" 'compiler error - did not define with Dim

            recurse = recurse + 1

            Console.WriteLine(TestCrazyAssignment)

            If recurse < 10 Then
                 TestCrazyAssignment()
            End If

            Return "umm.... ok."
        End Function
    End Class
End Class

输出:

this should not be possible.
this should not be possible.
this should not be possible.
this should not be possible.
this should not be possible.
this should not be possible.
this should not be possible.
this should not be possible.
this should not be possible.
this should not be possible.
umm.... ok.

在我的简单示例中,我想防止无限递归,但你明白了。

有没有人对此有一些见解?我最近在生产代码中遇到了这个问题。

4

1 回答 1

8

这是为函数设置返回值的传统 VB 方法。VB 提供了一个未声明的局部变量,其名称与函数名相同。我强烈建议不要这样做,而是使用显式的 return 语句。

(如果您不通过标准的“返回”退出,则未声明变量中的值将自动返回)。

于 2013-03-20T00:14:10.993 回答