我写了这个例子来帮助解释。如您所见,我有一个对象层次结构。我想修改 GetFeatures() 函数以仅返回由我实例化的对象类型的构造函数添加的功能。例如,BasicModel.GetFeatures(new LuxuryModel()) 应该只返回特征“Leather Seats”和“Sunroof”。如果必须,我不介意使用反射。
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