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 ステートメントを使用することを強くお勧めします。

(標準の「Return」で終了しない場合、宣言されていない変数の値が自動的に返されます)。

于 2013-03-20T00:14:10.993 に答える