2013-03-20 54 views
0

我的VB.net代碼這個片段中,我試圖弄清楚爲什麼它是合法的:爲什麼這個奇怪的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. 

在我簡單的例子,我要防止無限遞歸,但你明白了。

有沒有人對此有所瞭解?我最近在生產代碼中打了這個。

回答

8

這是設置函數返回值的傳統VB方法。 VB使一個未聲明的本地變量可用,它與函數名稱相同。 我強烈建議不要這樣做,而是使用顯式返回語句。

(如果您不通過標準的「返回」退出,則未聲明的變量中的值將自動返回)。

+0

哇。很高興知道。謝謝! – dwerner 2013-03-20 00:14:44

+0

最後,我明白爲什麼有一個'退出函數' – dwerner 2013-03-20 00:21:30

+2

「無法弄清楚什麼是混亂」,前VB6程序員說。 – djv 2013-03-20 03:29:37

相關問題