在Mustinherit类-VB.NET中返回self类型
我有一个抽象类在Mustinherit类-VB.NET中返回self类型,vb.net,oop,inheritance,interface,Vb.net,Oop,Inheritance,Interface,我有一个抽象类 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)
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
我想添加一个共享函数
,例如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
调用继承的SpecificClass
的magicFunction
应返回SpecificClass
的对象,如下所示:
Public Class ABC
Public Function myAwesomeFunction as SpecificClass
Dim objSpecificClass as SpecificClass
objSpecificClass = SpecificClass.magicFunction(someInteger)
Return objSpecificClass
End Sub
End Class
任何帮助都将不胜感激这可能有助于:
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)
可能的副本必须使用反射。类似于:
Activator.CreateInstance(Me.GetType)
@user1937198-我在这里发布问题之前阅读了这个问题并给出了答案。这不是我问题的重复。让我谷歌一下你的第二个建议-Activator.CreateInstance(Me.GetType)
你的泛型类“
不是泛型类。明白了。很好,正是我想要的。