级联类属性vb.net

时间:2017-05-23 15:05:58

标签: vb.net

这3个类结构是我的代码的简化视图:

基类:

Public Class A

    Public x As Integer

    Protected Function G() as Integer
       Return x
    End Function

    Protected Sub S(value as Integer)
         x = value
    End Sub

    Public Function Test()
         Return x + 10
    End Function

End Class

子类:

Public Class B

    Inherits A

    Public Property Prop As Integer
        Get
            Return G()
        End Get
        Set(ByVal Value As Integer)
            S(Value)
        End Set
    End Property

End Class

Public Class C

    Inherits A

    Public InnerB As New B

End Class

目标是能够编写类似的代码:

Dim B1 as New B
Dim C1 as New C

B1.Prop = 10
C1.InnerB.Prop = 20 'the "x" member inherited from A takes the value 20 for the InnerB object but not for the C1 object.

MsgBox(B1.Test()) ' returns 20. Works!
MsgBox(C1.Test()) 'returns 10 instead of 30.

是否可以通过从内部类B调用“prop”来填充C中继承的“x”成员?

1 个答案:

答案 0 :(得分:0)

设置

C1.InnerB.Prop = 20

实际上

C1.InnerB.x = 20

致电时

C1.Test()

它将访问

C1.x

而不是

C1.InnerB.x

您需要致电

MsgBox(C1.InnerB.Test()) 

或覆盖测试功能

Public Class C
    Inherits A

    Public InnerB As New B

    Public Overrides Function Test()
         Return InnerB.Test()
    End Function

End Class

但你正在做的是......很奇怪