2012-03-31 82 views
3

我有是令人沮喪的我沒有盡頭的一個問題,我有一個父類覆寫投放功能,並在子類覆蓋功能,如下圖所示:如何使用父類中子類的值? vb.net

子類

Public Overrides Sub UpdatePrice(ByVal dblRetailPrice As Double) 
    If dblWholesalePrice < 0 Then 
     MessageBox.Show("Error, amount must be greater than 0.") 
    Else 
     dblRetailPrice = dblWholesalePrice * dblStandardMargin 
    End If 
End Sub 

,並在父類中,我有

Public ReadOnly Property RetailPrice() As Double 
    Get 
     Return dblRetailPrice 
    End Get 
End Property 

Public Overridable Sub UpdatePrice(ByVal dblRetailPrice As Double) 
    If dblWholesalePrice < 0 Then 
     MessageBox.Show("Please input an amount greater than 0,wholesale price has not changed", "error") 
    Else 
     dblRetailPrice = 1.1 * dblWholesalePrice 
    End If 
End Sub 

當我調試,產生的價值,但它並沒有延續到父類ski.RetailPrice()的,似乎是什麼問題這裏?任何幫助將不勝感激。

+1

-0.25仍然使用匈牙利命名法:P – cHao 2012-03-31 06:03:19

回答

2

您不應該在較高範圍內傳入與具有相同名稱的參數作爲類級變量。局部變量將覆蓋其他的,這意味着這一說法在二傳手:

dblRetailPrice = 1.1 * dblWholesalePrice 

將設置你剛剛過去的,不是你的類級dblWholesalePrice成員變量​​臨時參數的值。

簡單的解決辦法就是通過丟棄無用的類型符號前綴更改參數的名稱:

Public Class MyClass 

    Protected dblRetailPrice As Double 

    Public ReadOnly Property RetailPrice() As Double 
     Get 
      Return dblRetailPrice 
     End Get 
    End Property 

    Public Overridable Sub UpdatePrice(ByVal retailPrice As Double) 

     If dblWholesalePrice < 0 Then 
      MessageBox.Show("Please input an amount greater than 0,wholesale price has not changed", "error") 
     Else 
      dblRetailPrice = 1.1 * dblWholesalePrice 
     End If 
    End Sub 

End Class 
+0

這將是更好的消除類前綴總之,無處不在。另外,當方法被覆蓋時,認爲'Private'成員不能在子類中訪問。該成員將需要被「保護」。 – TLS 2012-03-31 05:49:49

+0

@TLS:是的,會的。但這並不重要。這僅僅是一種文體選擇。由於VB.NET不區分大小寫,我用pascalCase命名字段的典型策略失敗了,我傾向於在開始時追加同樣難看的'm_'。我只是想盡量避免在這裏過分複雜化。是的,關於'Protected'的好處;那是我的錯誤。 – 2012-03-31 05:52:16

+0

這絕對是一種文體選擇,因爲我的團隊偏好使用「_」作爲所有「私人」成員的前綴。當然,在這種情況下,我們正在談論「受保護」。無論哪種方式,在我的書中都有+1。 – TLS 2012-03-31 05:54:21

相關問題