Question

I am trying to implement a mySubClass.vb file as a nested subclass of another main class. It seems like the Partial Class idea is what I need but the implementation isn't working when I try to pull mySubClass.vb in as a nested subclass of another main class.

My original implementation of this code used mySubClass directly so I know the functionality works. I just want to use mySubClass as a data structure within clsMain.

Main Class

Public Class clsMain

    Public Property myIntProp as Integer
    Public property myStrProp as String
    'other properties

    Partial Public Class MySubClass
        'I want this functionality to be accessible via clsMain.MySubClass
        'Just like any other property or function of clsMain
        'Partial would keep things organized nicely
    End Class
End Class

Sub Class

The class.vb that I want to use as clsMain.MySubClass. File: MySubClass.vb

Partial Public Class MySubClass
    Inherits BaseCollection

    Private Class MySubSubClass '(Used for custom properties and functions)
        'More properties and Functions
    End Class
End Sub

Public Class BaseCollection 'functionality of MySubClass
    Public Function MyFunction1()
        'Return Data
    End Function
End Class

How Main Class is Used

Public Class UsageClass
    Private myMainDataStructure as new clsMain

    Private Sub GetSubClassList()
        dim MyData as ArrayList = myMainDataStructure.MySubClass.MyFunction1() 
        '^^^ error on this line: MyFunction1() is not a member of project.clsMain.MySubClass^^^
    End Sub
End Class
Était-ce utile?

La solution

Instead of trying to make this a Partial Class, you should just make a Property containing an instance of that class.

Nested classes must be created and have instances, just like top level classes. By making a property within your main class, you can automatically create that instance in your main class constructor, and your code will work as expected.

Public Class clsMain

    Public Property myIntProp as Integer
    Public property myStrProp as String
    'other properties

    Public Property OtherFunctionality as MyOtherClass = New MyOtherClass()

Then just define the class in a separate file:

Public Class MyOtherClass
    Public Sub MyFunction1()
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top