VB.Net Tutorial/Class Module/Class Cast

Материал из VB Эксперт
Перейти к: навигация, поиск

Downcast: cast base-class reference to derived-class

Class Tester
   
   Shared Sub Main()
      Dim point1, point2 As Point
      Dim circle1, circle2 As Circle
      point1 = New Point(30, 50)
      circle1 = New Circle(120, 89, 2.7)
      Console.WriteLine("Point point1: " & point1.ToString() & _
         vbCrLf & "Circle circle1: " & circle1.ToString())
      point2 = circle1
      Console.WriteLine("Circle circle1 (via point2): " & point2.ToString())
      circle2 = CType(point2, Circle) " allowed only via cast
      Console.WriteLine("Circle circle1 (via circle2): " & circle2.ToString())
      If (TypeOf point1 Is Circle) Then
         circle2 = CType(point1, Circle)
         Console.WriteLine("cast successful")
      Else
         Console.WriteLine("point1 does not refer to a Circle")
      End If
   End Sub
End Class 
Public Class Point
   Private mX, mY As Integer
   Public Sub New()
   End Sub " New
   Public Sub New(ByVal xValue As Integer, _
      ByVal yValue As Integer)
   End Sub " New
   Public Overrides Function ToString() As String
      Return "[" & mX & ", " & mY & "]"
   End Function " ToString
End Class
Public Class Circle
   Inherits Point 
   Private mRadius As Double
   Public Sub New()
   End Sub " New
   Public Sub New(ByVal xValue As Integer, _
      ByVal yValue As Integer, ByVal radiusValue As Double)
      MyBase.New(xValue, yValue)
   End Sub " New
   Public Overrides Function ToString() As String
      Return "Center= " & MyBase.ToString() & _
         "; Radius = " & mRadius
   End Function " ToString
End Class
Point point1: [0, 0]
Circle circle1: Center= [0, 0]; Radius = 0
Circle circle1 (via point2): Center= [0, 0]; Radius = 0
Circle circle1 (via circle2): Center= [0, 0]; Radius = 0
point1 does not refer to a Circle