我有名为ParentClass的MustInherit类。 我需要能够在不同的地方写下以下内容:
Function TheThing(Of T As ParentClass)(s As String) As ParentClass
Return New T(s)
End Function
我会写
MustInherit Class ParentClass
MustOverride Sub New(s As String)
End Class
Class Class_Daughter1
Inherits ParentClass
Overrides Sub New(s As String)
'do whatever
End Sub
End Class
事实上:
有没有办法做到这一点?我尝试使用一个Implements,但它没有成功......
PS:如果我只是使用
Function TheThing(Of T As ParentClass)(s As String) As ParentClass
dim a as new T()
Return a
End Function
新行不起作用
PS2:这也是不允许的:
Function TheThing(Of T As {ParentClass, iCreatable})(s As String) As ParentClass
Return New T(s)
End Function
Interface iCreatable
Sub New() '===> not allowed in interface
End Interface
答案 0 :(得分:2)
类的构造函数不能是MustInherit,但如果你想做一些基本相同的东西,你可以这样做:
MustInherit Class ParentClass
Protected Sub New(s As String)
Initialize(s)
End Sub
Protected MustOverride Sub Initialize()
End Class
您的Daughter类的构造函数必须调用MyBase.New(s)
。这样子类需要实现初始化,因为子类需要调用基类构造函数,所以保证将调用Initialize。
答案 1 :(得分:0)
我刚刚得到答案(来自朋友):
Function TheThing(Of T As {New, ParentClass})(s As String) As ParentClass
Dim res As New T()
res.Init(s)
Return res
End Function
MustInherit Class ParentClass
MustOverride Sub Init(s As String)
End Class
Class Class_Daughter1
Inherits ParentClass
Overrides Sub Init(s As String)
'do whatever
End Sub
End Class
我唯一无法解决的问题是:我不能写下面的内容(如果编译的话,它将是相同的,但在编译时会相同):
Function TheThing(Of T As {New(s as string), ParentClass})(s As String) As ParentClass
return New T(s)
End Function
MustInherit Class ParentClass
'nothing here
End Class
Class Class_Daughter1
Inherits ParentClass
public Sub New(s As String)
'do whatever
End Sub
End Class