2012-03-06 44 views
2

我知道當談論陰影和重載時,VB.net非常奇怪,但是這個我完全被困惑了。陰影在函數中使用時表現得很奇怪

我正在使用與以下類似的模型。父類:

Public Class Base 
    Function F() As String 
     Return "F() in Base Class" 
    End Function 

    Function F(ByVal n As Integer) As String 
     Return "F(" + n.ToString() + ") in Base Class" 
    End Function 
End Class 

這:

Class Derived 
    Inherits Base 
    Shadows Function F() As String 
     Return "-" 
    End Function 
End Class 

運行以下時:

Sub Main() 
    Dim parent As Base = New Base() 
    Dim child As Derived = New Derived() 

    Console.WriteLine(parent.F()) 
    Console.WriteLine(parent.F(1)) 
    Console.WriteLine("------------") 

    Console.WriteLine(child.F()) 
    Console.WriteLine(child.F(1)) 'this should not compile, due to the shadow keyword. 

    Console.Read() 
End Sub 

一個IndexOutOfRangeException異常。此外,在更改時(在派生類中): 返回「 - 」 for 返回「派生類中的函數」 控制檯打印字符'u'。 有人知道這個的原因嗎?

回答

3

你的代碼索引String而不是用參數調用函數。

Console.WriteLine(child.F(1)) 

這條線被擴展爲:

Dim childFResult As String = child.F() 
Dim character As Char = F.Chars(1) ' Failure here. 
Console.WriteLine(character) 

因爲String.Chars是默認屬性,您可以通過索引單獨引用它。您的字符串只包含一個字符,因此索引1處沒有字符。

5

您的F是一個字符串,所以當您指定索引時,它將查看字符串的索引,而不是使用整數參數的第二個函數。

「U」是在「功能」的第二個字符,由索引1

指定你的榜樣,你就必須陰影第二功能,太:

Class Derived 
    Inherits Base 

    Shadows Function F() As String 
    Return "-" 
    End Function 

    Shadows Function F(ByVal n As Integer) As String 
    Return "X" 
    End Function 
End Class 
3

這是vb.net中的語法歧義,()可以表示「方法調用」和「數組索引」。您獲得了數組索引版本,索引1超出了F()返回的字符串的範圍。或者換句話說,編譯器編譯如下:

Console.WriteLine(child.F(1)) 

這樣:

Dim temp1 As String = child.F() 
Dim temp2 As Char = temp1(1) 
Console.WriteLine(temp2) 

第二條語句導致異常。這就是生活。

相關問題