从带参数的主类构造函数中调用不带参数的派生类构造函数

时间:2019-04-09 12:19:29

标签: vb.net class constructor

我有一个抽象基类和一个派生类。基类有一些我想根据派生类类型设置的成员。但是对于所有接受参数的派生类,我也有一个通用的构造函数。带有参数的通用构造函数正在重复我想摆脱的代码。

Public MustInherit Class B
    Protected member1 As String
    Protected member2 As String
End Class

Public Class D1 : Inherits B
    Public Sub New()
        Me.member1 = "D1" ' individual code here
    End Sub

    Public Sub New(arg As String)
        Me.New()
        Me.meber2 = arg ' repeating code here, should be moved to base class
    End Sub
End Class

Public Class D2 : Inherits B
    Public Sub New()
        Me.member1 = "D2" ' individual code here
    End Sub

    Public Sub New(arg As String)
        Me.New()
        Me.meber2 = arg ' repeating code here, should be moved to base class
    End Sub
End Class

我该如何重构它,以便即使在基类中使用带有参数的构造函数时也调用没有参数的派生构造函数?

2 个答案:

答案 0 :(得分:1)

为什么不向基类添加构造函数?

Public MustInherit Class B
    Public Sub New(arg As String)
        Me.member2 = arg
    End Sub

    Protected member1 As String
    Protected member2 As String
End Class

Public Class D1 : Inherits B
    Public Sub New(arg As String)
        MyBase.New(arg)
        Me.member1 = "D1"
    End Sub
End Class

Public Class D2 : Inherits B
    Public Sub New(arg As String)
        MyBase.New(arg)
        Me.member1 = "D2"
    End Sub
End Class

它本身并没有真正减少重复,因为每个派生类仍然具有调用基本构造函数的行,并为其传递值,但是它确实允许您集中维护使用该值执行的操作,并且它确实强制所有派生类都这样做。这样,您将永远无法创建派生类,而您忘了提供该值。

实际上,如果您想要求所有派生类为member1提供默认值,则也可以将其作为参数添加到基本构造函数中:

Public MustInherit Class B
    Public Sub New(member1 As String, member2 As String)
        Me.member1 = member1
        Me.member2 = member2
    End Sub

    Private member1 As String
    Private member2 As String
End Class

Public Class D1 : Inherits B
    Public Sub New(arg As String)
        MyBase.New("D1", arg)
    End Sub
End Class

Public Class D2 : Inherits B
    Public Sub New(arg As String)
        MyBase.New("D2", arg)
    End Sub
End Class

答案 1 :(得分:1)

由于成员是Private,因此您的代码甚至无法编译。您可以使用填充成员的Protected方法。

Public MustInherit Class B
    Private member1 As String
    Private member2 As String

    Protected Sub SetMembers(ByVal m1 As String, ByVal m2 As String)
        member1 = m1
        member2 = m2
    End Sub

End Class

Public Class D1 : Inherits B
    Public Sub New()
        Me.New("")
    End Sub

    Public Sub New(arg As String)
        SetMembers("D1", arg)
    End Sub
End Class

Public Class D2 : Inherits B
    Public Sub New()
        Me.New("")
    End Sub

    Public Sub New(arg As String)
        SetMembers("D2", arg)
    End Sub
End Class

如果需要,可以将SetMembers更改为受保护的New,然后使用MyBase.New(...,...)对其进行调用。