为什么这种奇怪的VB.net行为允许赋值给函数?

dwe*_*ner 0 vb.net syntax function

我有这个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
Run Code Online (Sandbox Code Playgroud)

输出:

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.
Run Code Online (Sandbox Code Playgroud)

在我琐碎的例子中,我想阻止无限递归,但你明白了.

有没有人对这个有一些见解?我最近在生产代码中看到了这个.

Dav*_*jas 8

这是设置函数返回值的传统VB方法.VB生成一个未声明的局部变量,其名称与函数名称相同.我强烈建议不要使用显式返回语句.

(如果不通过标准'Return'退出,则自动返回未声明变量中的值).

  • "无法弄清楚什么令人困惑",前VB6程序员说. (2认同)