が、私は3つのオプションを見ていると同じからそれらの両方を導き出す
Class FruitStand(Of TFruit As Fruit)
Public ReadOnly Property Contents As List(Of TFruit)
End Class
NotInheritable Class AppleCart
Inherits FruitStand(Of Apple)
End Class
それとも、代わりにFruitStand
とAppleCart
との関係を断つ、新たに抽出されました基底クラス(私はこれがneatestオプションだと思う):私は、派生を封印してきたいずれの場合も
MustInherit Class FruitStandBase(Of TFruit As Fruit)
Public ReadOnly Property Contents As List(Of TFruit)
End Class
NotInheritable Class FruitStand
Inherits FruitStandBase(Of Fruit)
End Class
NotInheritable Class AppleCart
Inherits FruitStandBase(Of Apple)
End Class
AppleCart
から派生した型は、TFruit
の型をオーバーライドできます。階層のその時点でタイプContents
が閉じられます。
最後に、シャドーイングを使用して、より派生型のContents
の意味を変更することができます。キャッチは:ベースタイプのContents
プロパティ(つまり、IReadOnlyList(Of Fruit)
などの読み取り専用インターフェイスまたは配列を使用して、要素を追加または削除することができなくなる)の共変コレクションを使用する必要があります。
Class FruitStand
Public ReadOnly Property Contents As IReadOnlyList(Of Fruit)
Public Sub New()
Me.New(New List(Of Fruit))
End Sub
Protected Sub New(contents As IReadOnlyList(Of Fruit))
Me.Contents = contents
End Sub
End Class
Class AppleCart
Inherits FruitStand
Public Shadows ReadOnly Property Contents As IReadOnlyList(Of Apple)
Get
Return CType(MyBase.Contents, IReadOnlyList(Of Apple))
End Get
End Property
Public Sub New()
MyBase.New(New List(Of Apple))
End Sub
End Class
AppleCartにはAppleのみを含めることができますが、なぜそれをキャストする必要がありますか? – Plutonix
AppleCartがFruitStandから継承するのではなく、おそらくインターフェイス(例えば、IFruitVendor(of T))があなたの望むことをするでしょう。 – Plutonix
スーパークラスを取り戻す(FruitStand)Appleのリストではなく、フルーツのリストを返します。そのため、消費者は、Appleに固有のプロパティにアクセスするために、列挙者から返されたFruitをAppleにキャストする必要があります。 AppleカートにはApplesのみが含まれているため、Applesのみがリストに追加されます。 – rcp