【问题标题】:Custom Classes and Collection Classes自定义类和集合类
【发布时间】:2017-02-21 12:02:05
【问题描述】:

我有一些自定义类和这些类的集合类。我对实际实施所有这些有点陌生,我看到了很多不同的选择,但都有各自的优缺点,而且我在确定做我需要的最佳/正确方法时遇到了麻烦。

例如,我有一个带有 ID 和 Description 属性的 Product 类。我有一个 ProductCollection 类,我基本上想成为一个由 Product 对象组成的字典。这是一个字典,因为通过键值访问可以提高性能,这就是我将引用对象的方式。键是 Product.ID,值是 Product。

我希望能够执行 ProductCollection.Add(Product) 之类的操作,并且该集合将处理从对象的 ID 属性对字典键进行签名。我怎样才能最好地做到这一点?实现 Dictionary(Of Integer, Product) 并覆盖基本上所有方法以分别传入对象和属性?还是有更好的办法?

此外,为了提供更多背景信息以帮助阐明这些类的用法,将有一个 ProductCollection 的“主”实例,其中包含所有可能的产品。 ShipTo 类还将有一个 ProductCollection,其中包含适用于该特定 ShipTo 的特定产品。我的问题是针对 Product/ProductCollection 类的,但也适用于 ShipTo 类。

【问题讨论】:

  • 集合和集合类是有区别的。后者要么继承自一个集合(如Collection(of T))以添加您需要的功能,要么封装某些方面。否则 Q 有点宽
  • 你应该继承KeyedCollection类:msdn.microsoft.com/en-us/library/ms132438(v=vs.110).aspx
  • Plutonix:对不起,我指的是集合类,我会更新问题以澄清。话虽如此,我认为我的问题非常具体。
  • jmcilhinney:谢谢,这看起来正是我所需要的。在将其与 Dictionary 进行比较时,我忽略了它,因为 KeyedCollection 的“好处”是它使项目保持与添加到集合中的顺序相同,但以牺牲性能为代价。由于这不是我想要的好处,所以我一直在寻找其他东西。

标签: vb.net oop dictionary inheritance collections


【解决方案1】:

这就是我持有产品集合的方式。我有一个Product 类和一个Products 集合类。

首先创建包含所有属性的Product 类:

Imports System.Collections.ObjectModel
Public Class Product
Public Key As String

   Public Sub New(ByVal id As Integer,
                  ByVal description As String)

      _id = id
      _description = description

   End Sub

   Private _id As Integer
   Public ReadOnly Property ID() As Integer
      Get
          Return _id
      End Get

   End Property

   Private _description As String
   Public ReadOnly Property Description() As String
      Get
          Return _description
      End Get
   End Property

End Class

创建一个Products集合类来保存Product类:

Public Class Products
Inherits KeyedCollection(Of String, Product)

   Protected Overrides Function GetKeyForItem(ByVal item As Product) As String
       Return item.Key
   End Function

End Class

然后你会像这样使用它们:

Dim myProducts As New Products
myProducts.Add(New Product(1,"Table"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 2017-08-23
    • 1970-01-01
    相关资源
    最近更新 更多