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

荒凉一梦 提交于 2019-12-07 06:47:37

问题


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, code in VB.net or C# is appreciated, Thanks.


回答1:


The inner class (class2) is not associated with any specific instance of the outer class (class1). T access fields etc, you will need to first have an explicit reference to a class1 instance, probably passing it in via 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



回答2:


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

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

This way Class2 doesn't have access to all of Class1's variables and properties; only what you explicitly give it. Usually we don't want the child class to be in control of the parent class. So this method provides that separation.



来源:https://stackoverflow.com/questions/8692475/how-to-get-a-value-inside-parent-class-from-child-class-in-nested-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!