我試圖讓我的頭回到VB.Net(已經有一段時間)和 似乎無法解決這個簡單的問題。VB.Net類型轉換
這裏是我的抽象基類及其接口:
Imports VBRefresh.Animal
Public Interface IAnimal
ReadOnly Property AnimalType() As TypeOfAnimal
Property IsAlive As Boolean
End Interface
Public MustInherit Class Animal
Implements IAnimal
Public Enum TypeOfAnimal
Insect
Mammal
Fish
Bird
Reptile
End Enum
Private _animalType As TypeOfAnimal
Public ReadOnly Property AnimalType As TypeOfAnimal Implements IAnimal.AnimalType
Get
Return _animalType
End Get
End Property
Private _isAlive As Boolean
Public Property IsAlive() As Boolean Implements IAnimal.IsAlive
Get
Return _isAlive
End Get
Set(ByVal value As Boolean)
_isAlive = value
End Set
End Property
Public Sub New(animalType As TypeOfAnimal)
_animalType = animalType
End Sub
End Class
而且這裏有兩個派生類(其中Cow
是擴大IAnimal
):
Public Interface ICow
Inherits IAnimal
Property FriendlyName As String
End Interface
Public Class Cow
Inherits Animal
Implements ICow
Public Sub New()
MyBase.New(TypeOfAnimal.Mammal)
End Sub
Private _friendlyName As String
Public Property FriendlyName As String Implements ICow.FriendlyName
Get
Return _friendlyName
End Get
Set(value As String)
_friendlyName = value
End Set
End Property
End Class
Public Class Eagle
Inherits Animal
Public Sub New()
MyBase.New(TypeOfAnimal.Bird)
End Sub
End Class
我試圖改變類型myAnimal
到Cow
所以我可以訪問它的屬性FriendlyName
但我不能讓它在沒有
- 創建一個單獨的對象並進行設置。
在
IAnimal
接口聲明FriendlyName
.. 我試圖鑄造myAnimal
到ICow
但是,這並不讓我獲得了FriendlyName
財產?Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load Dim myAnimal As IAnimal = New Eagle myAnimal.IsAlive = True myAnimal = New Cow myAnimal.FriendlyName = "Bella" 'this line doesn't work Dim myCow As ICow = New Cow myCow.FriendlyName = "Bella" MessageBox.Show(myAnimal.AnimalType.ToString) End Sub
可能是一些愚蠢的,但我在這裏跑出來的選擇。
謝謝,我已經知道這一點,但我需要一個來自myAnimal的對象ICow。 – grmbl