我有一个抽象类
Public MustInherit Class GenericClass
Public Sub New(Byval x as Integer)
' Some code here
End Sub
End Class
我将这个类继承到另一个类,如下所示:
Public Class SpecificClass
Inherits GenericClass
Public Sub New(Byval x as Integer)
MyBase.New(x)
End Sub
End Class
我想添加一个Shared Function
,例如magicFunction
以这样一种方式,当我使用它时,它应该返回一个SpecificClass
类型的对象。我该怎么办?
我想要这样的东西,但VB.NET中不允许这样做
Public MustInherit Class GenericClass
Public Sub New(Byval x as Integer)
' Some code here
End Sub
Public Shared Function magicFunction(Byval y as Integer) as GenericClass
Dim z as Integer
' Some code here that will alter the value of z
Return New GenericClass(z) ' Not allowed in VB.NET -- MustInherit class cannot have new
End Sub
End Class
调用继承magicFunction
的{{1}}应该返回SpecificClass
这样的对象:
SpecificClass
任何帮助将不胜感激
答案 0 :(得分:1)
这可能有所帮助:
Public MustInherit Class GenericClass(Of T As {GenericClass(Of T)})
Public Sub New(ByVal x As Integer)
' Some code here
End Sub
Public Shared Function magicFunction(ByVal y As Integer) As GenericClass(Of T)
Dim z As Integer
' Some code here that will alter the value of z
Return Activator.CreateInstance(GetType(T), z)
End Function
End Class
Public Class SpecificClass1
Inherits GenericClass(Of SpecificClass1)
Public Sub New(ByVal x As Integer)
MyBase.New(x)
End Sub
End Class
Public Class SpecificClass2
Inherits GenericClass(Of SpecificClass2)
Public Sub New(ByVal x As Integer)
MyBase.New(x)
End Sub
End Class
用法:
Dim a As SpecificClass1 = SpecificClass1.magicFunction(1)
Dim b As SpecificClass2 = SpecificClass2.magicFunction(2)