如何使用父类中子类的值? vb.net

时间:2012-03-31 05:37:18

标签: 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 :(得分:2)

您不应该在更高的范围内传入与类级变量同名的参数。局部变量将覆盖另一个,这意味着你的setter中的这个语句:

dblRetailPrice = 1.1 * dblWholesalePrice

将设置您刚刚传入的dblRetailPrice临时参数的值,而不是您的类级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