How to get value inside parent class from child class (in nested classes)?

I have Class1 and class2, which is inside class1, VB.NET code:

Public Class class1
    Public varisbleX As Integer = 1
    Public Class class2
        Public Sub New()
            'Here GET the value of VariableX
        End Sub
    End Class

    Public Sub New()
        Dim cls2 As New class2
    End Sub
End Class

I want to access varisbleX from class2, the code in VB.net or C # is appreciated, thanks.

+5
source share
2 answers

The inner class (class2) is not associated with any particular instance of the outer class (class1). T, etc., you first need to get an explicit reference to an instance of class1, possibly passing it through the constructor. For example, it could be:

Public Class class1
    Public varisbleX As Integer = 1
    Public Class class2
        Public Property Parent As class1

        Public Sub New(oParent As class1)
            Me.Parent = oParent
            Console.WriteLine(oParent.varisbleX)
        End Sub
    End Class

    Public Sub New()
        Dim cls2 As New class2(Me)
    End Sub
End Class
+8
source

If you need only a few variables, you can pass the variable (s) as a parameter when initializing class 2.

Public Class Class1

    Public VariableX As Integer = 1

    Public Class Class2
        Public Sub New(ByVal VariableX As Integer)
            'Here GET the value of VariableX
            Debug.Print(VariableX)
        End Sub
    End Class

    Public Sub New()
        Dim cls2 As New Class2(VariableX)
    End Sub

End Class

, Class2 Class1; , . , . , .

0

All Articles