VB从基类返回派生类实例

时间:2017-09-29 11:13:49

标签: vb.net inheritance

我正在尝试创建一个可以继承并用于菊花链调用的基类,但我要求返回的对象是派生类。

考虑:

Public Class MyElement
    Public Function SetAttribute(name As String, value As String) As MyElement
        // Set the attribute
        Return Me
    End Function
End Class

Public Class ExtendedElement
    Inherits MyElement

    Public Sub DoSomething()
        // Code to do something
    End Sub
End Class

// What I would like to achieve

Dim my_var As New ExtendedElement
my_var.
    SetAttribute("FirstName", "Bob").
    SetAttribute("LastName", "Builder").
    DoSomething()

这种事情有可能吗?

2 个答案:

答案 0 :(得分:2)

你有几个选择,而不是直截了当。

<强>铸造

您可以转换返回的值。

    Dim my_var As New ExtendedElement
    CType(my_var.
        SetAttribute("FirstName", "Bob").
        SetAttribute("LastName", "Builder"), ExtendedElement).
        DoSomething()

<强>重写

您可以在子类中添加DoSomething并将功能放在父级中。

Public Class MyElement
    Public Function SetAttribute(name As String, value As String) As MyElement
        Return Me
    End Function

    Public Overridable Sub DoSomething()
    End Sub

End Class

Public Class ExtendedElement
    Inherits MyElement

    Public Overrides Sub DoSomething()
        ' Do logic here
    End Sub

End Class

    my_var.
        SetAttribute("FirstName", "Bob").
        SetAttribute("LastName", "Builder").
        DoSomething()

<强>泛型

使父类成为通用类,以返回正确的子类。

Public Class MyElement(Of T As MyElement(Of T))
    Public Function SetAttribute(name As String, value As String) As T
        Return Me
    End Function
End Class

Public Class ExtendedElement
    Inherits MyElement(Of ExtendedElement)

    Public Sub DoSomething()
        ' Do logic here
    End Sub

End Class

    Dim my_var As New ExtendedElement
    my_var.
        SetAttribute("FirstName", "Bob").
        SetAttribute("LastName", "Builder").
        DoSomething()

答案 1 :(得分:0)

您可以这样做:

Dim MyVar as new ExtendedElement
Ctype(MyVar.SetAttribute("FirstName", "Bob"). _
      SetAttribute("LastName", "Builder"), ExtendedElement).DoSomething()