VB: How do I create nested classes?

2019-09-07 11:24发布

问题:

I would like to write a nested class into an existing class of my own. But I can't find how because I have no idea how this is really called.

What do I mean by nested class? With a table dt from the DataTable class, I can write dt.Columns.add(). Columns would be property of the main class and add would be a method from a nested class.

Any suggestions?

回答1:

That is not a nested class, it's simply a class. The Columns property is of the type DataColumnCollection that has a public method called Add. To build your own in a similar fashion it would simply be:

Public Class MyFirstClass

    Public Sub New()

    End Sub

    Dim _second As New MySecondClass()
    Public Property Second() As MySecondClass
        Get
            Return _second
        End Get
        Set(ByVal Value As MySecondClass)
            _second = Value
        End Set
    End Property
End Class

Public Class MySecondClass
    Public Sub New()
    End Sub

    Public Sub MySecondClassMethod()
        'Do something
    End Sub
End Class

This would then be called in some other class or functionality like:

Dim x as New MyFirstClass()
x.Second.MySecondClassMethod()


标签: vb.net class