【问题标题】:Casting Objects at runtime在运行时投射对象
【发布时间】:2015-01-10 11:40:52
【问题描述】:

请看下面的代码:

  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?

【问题讨论】:

  • 您不需要将他们转换为不同类型的学生。也许您应该改用接口?
  • 根据不同的差异,基类上的 StudentType 属性也可能有所帮助。

标签: .net vb.net inheritance casting abstract-class


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多