Yuk Tang <ji********@yah oo.com> wrote in
news:Xn******** *************** ********@130.13 3.1.4:
Leading on from a recent topic, "How does child class access
parent's variables", I would like to ask, what's the most elegant
way of changing a parent/grandparent/great-grandparent's property?
The class Nest has a subclass SubNest. Within SubNest I want to
work with Title. I think if I can pass Title ByRef to the
children and grandchildren, it would work, but VB doesn't do so by
default, and indeed warns me against it: "Reference to a
non-shared member requires an object reference."
I've done a modified version of this, with the parent having a
property that holds the child, and vice versa. So
Parent.Child.Pa rent,etc. I've also included a Title property in the
Parent to let me see what's going on.
Public Class Nest
Private mstrTitle As String
Private mstrSubNests As SubNest
Public Property Title() As String
Public Property SubNests() As SubNest
Public Class SubNest
Private mstrParent As Nest
Public Property Parent() As Nest
End Class
Public Sub New()
Dim sn As New SubNest
SubNests = sn
End Sub
End Class
Private Sub Button1_Click(B yVal sender As System.Object, ByVal e
As System.EventArg s) Handles Button1.Click
Dim n As New Nest
n.Title = "Hello"
n.SubNests.Pare nt = n
MsgBox("Origina l: " + n.Title)
MsgBox("Nested: " + n.SubNests.Pare nt.Title)
n.SubNests.Pare nt.Title = "There"
MsgBox("Origina l: " + n.Title)
MsgBox("Nested: " + n.SubNests.Pare nt.Title)
n.Title = n.SubNests.Pare nt.Title
MsgBox("Origina l: " + n.Title)
MsgBox("Nested: " + n.SubNests.Pare nt.Title)
End Sub
So this creates a Parent, sets its Title to "Hello", and sets
Child.Parent to Parent. So Parent.Title and Child.Parent.Ti tle
should both be "Hello". This is indeed the case.
Hello, Hello
The next step sets Child.Parent.Ti tle to "There", but leaves
Parent.Title alone. The expected result should therefore be "Hello"
and "There". However, this is what I get.
There, There
The last step should set Parent.Title to "There" as well, but it
seems that's already been done in step 2.
There, There
Doing further experiments, it looks as though setting one
automatically sets the other. Can anyone explain scopes or whatever
it is that's going on?
--
Cheers, ymt.