2017-04-09 18 views
0

我有一個函數,當我打電話時,它讓我不用(),爲什麼?以同樣的方式調用函數和屬性?

Public Class Socio 

Private _antiguedad As Integer 

Public Function RetornarAntiguedad() As Integer 
     Return _antiguedad 
    End Function 
End Class 

Sub Main() 
    Dim test = New Socio() 
    test.RetornarAntiguedad <--- This works even though it doesnt have(), why? 
    Console.ReadKey() 
End Sub 

它看起來像一個屬性?它不會在函數和屬性之間產生混淆?

回答

0

在VB語法中,函數調用在捕獲其返回值時不需要尾隨()

在上面的示例中,您將像調用方法一樣調用該函數,而不捕獲其返回值。因此Visual Studio IDE應該自動附加括號。

但是,如果你把它改成這樣:

Dim test As New Socio() 
Dim result as Integer = test.RetornarAntiguedad 

...括號不再需要。

這只是VB.NET的語法,就是這樣。完全不用擔心。你的代碼仍然可以工作。

1

括號是可選的,編譯器因此不會返回錯誤,除非您正在添加參數。我認爲這是由於VB.Net的「靈活」設計。