请参阅以下代码:
Public Class Student
Public Shared Function Factory(ByVal somecriteria As String) As Student
'Return either a PostGraduate or UnderGraduate based on some criteria
End Function
End Class
Public Class PostGraduate
Inherits Student
End Class
Public Class UnderGraduate
Inherits Student
End Class
说我在应用程序中有这样的代码:
Dim s as Student = Student.Factory(somecriteria)
我如何根据Student.StudentFactory返回的内容,在运行时将s变量强制转换为PostGraduate或Undergraduate?
答案 0 :(得分:-1)
很难理解你想要在这里实现的目标,但要回答你的问题,你可以使用CType
转换为具体的类和GetType
来确定它要从哪个类开始用:
Dim s As Student = Student.Factory("")
If s.GetType Is GetType(PostGraduate) Then
Dim p As PostGraduate = CType(s, PostGraduate)
Else
Dim u As UnderGraduate = CType(s, UnderGraduate)
End If