我寫了這個例子來幫助解釋。正如你所看到的,我有一個對象層次結構。我想修改GetFeatures()函數以僅返回由實例化的對象類型的構造函數添加的功能。例如,BasicModel.GetFeatures(new LuxuryModel())應該只返回「皮革座椅」和「天窗」功能。如果必須的話,我不介意使用反射。如何基於創建的子類的類型過濾基類中的對象集合?
Public Class Feature
Public Sub New(ByVal model As BasicModel, ByVal description As String)
_model = model
_description = description
End Sub
Private _model As BasicModel
Public Property Model() As BasicModel
Get
Return _model
End Get
Set(ByVal value As BasicModel)
_model = value
End Set
End Property
Private _description As String
Public Property Description() As String
Get
Return _description
End Get
Set(ByVal value As String)
_description = value
End Set
End Property
End Class
Public Class BasicModel
Public Sub New()
_features = New List(Of Feature)
End Sub
Private _features As List(Of Feature)
Public ReadOnly Property Features() As List(Of Feature)
Get
Return _features
End Get
End Property
Public Shared Function GetFeatures(ByVal model As BasicModel) As List(Of Feature)
'I know this is wrong, but something like this...'
Return model.Features.FindAll(Function(f) f.Model.GetType() Is model.GetType())
End Function
End Class
Public Class SedanModel
Inherits BasicModel
Public Sub New()
MyBase.New()
Features.Add(New Feature(Me, "Fuzzy Dice"))
Features.Add(New Feature(Me, "Tree Air Freshener"))
End Sub
End Class
Public Class LuxuryModel
Inherits SedanModel
Public Sub New()
MyBase.New()
Features.Add(New Feature(Me, "Leather Seats"))
Features.Add(New Feature(Me, "Sunroof"))
End Sub
End Class
在VB中,這並不過濾任何東西。所有功能仍然返回。 – adam0101 2009-06-15 13:29:03