gpt4 book ai didi

.net - 如何根据创建的子类的类型过滤基类中的对象集合?

转载 作者:行者123 更新时间:2023-12-01 12:01:25 25 4
gpt4 key购买 nike

我写了这个例子来帮助解释。如您所见,我有一个对象层次结构。我想修改 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

最佳答案

如果您想保留当前的层次结构/属性,只需创建一个基类的实例,然后从派生类中的特性中减去基类中的特性。

或者,您可能需要考虑稍微更改您的类层次结构以使您自己更容易完成此操作。

例如,您可以将 Features 属性拆分为两个属性,比如 ModelFeatures 和 AllFeatures。

ModelFeatures 特定于当前模型(LuxuryModel 的“皮革座椅”和“天窗”等)。AllFeatures 返回 MyBase.AllFeatures 和 ModelFeatures 的联合。这使得获取当前模型的特征成为一种微不足道的属性访问。

附言请原谅我的 VB 错误,C# 是我的首选语言。

关于.net - 如何根据创建的子类的类型过滤基类中的对象集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/989338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com