Is there a way to create an instance of a subclass

2019-09-11 11:38发布

I'm writing classes which wrap around the TcpListener and TcpClient classes in VB. Currently here is my wrapper of the TcpListener class:

Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Public Class XXXTcpServer : Inherits TcpListener

    Public name As String

    Public clients As List(Of TcpClient)

    Public maxClients As Integer = -1

    ...

    Sub New(Optional ByVal name As String = "", Optional ByVal port As Int32 = 30000, Optional ByVal localAddr As IPAddress = Nothing)

        MyBase.New(If(localAddr, IPAddress.Any), Math.Max(IPEndPoint.MinPort, Math.Min(IPEndPoint.MaxPort, port)))

        Me.name = name
    End Sub

    Function acceptRequests() As Integer

        Dim accepted As Integer = 0

        While Pending() AndAlso (maxClients = -1 OrElse clients.Count < maxClients)

            Dim client As TcpClient = AcceptTcpClient()

            clients.Add(client)

            accepted += 1
        End While

        Return accepted
    End Function
End Class

However, it isn't a perfect wrapper because clients is a List(Of TcpClient) rather than a List(Of XXXTcpClient) (which is my wrapper class for TcpClient). I would like to make it the latter as the XXXTcpClient class has properties which stores additional information about the client which is needed.

The problem is that the AcceptTcpClient() method in the acceptRequests() function returns a TcpClient and I need to convert client into a XXXTcpClient in some way.

I was hoping for a solution like adding the following initialiser to the XXXTcpClient class:

Public Class XXXTcpClient : Inherits TcpClient

    ...

    Sub New(ByVal client As TcpClient)

        Me = client

        ...
        'Initialise all non-inherited variables to default values
        ...

    End Sub
End Class

and then using this in the acceptRequests() function instead:

Dim client As New XXXTcpClient(AcceptTcpClient())

but of course, that doesn't work.

Searching online seems to tell me that this is impossible to do, so I would appreciate a suggested solution to this problem.

0条回答
登录 后发表回答