代码之家  ›  专栏  ›  技术社区  ›  Aaron M

将派生类成员添加到自定义collectionbase时不可用

  •  0
  • Aaron M  · 技术社区  · 17 年前

    我有一个基类,叫做primitive Graphics。从这个类派生出几种不同类型的图形,正方形、矩形、直线等。

    Public Class PrimitiveCollection
        Inherits CollectionBase
        ''' <summary> 
        ''' Get or set a primitive object by index 
        ''' </summary> 
        Default Public Property Item(ByVal index As Integer) As Primitive
            Get
                Return DirectCast(List(index), Primitive)
            End Get
            Set(ByVal value As Primitive)
                List(index) = value
            End Set
        End Property
    

    3 回复  |  直到 17 年前
        1
  •  1
  •   Tom Ritter    17 年前

    您的问题是关于继承和接口的。以下是我的看法

    因此,在使用集合时,您有一个可绘制对象的集合。如果要将集合作为仅包含矩形的集合使用,则应使用列表<矩形>而不是原语的集合。

        2
  •  1
  •   Jon Skeet    17 年前

    如果要在单个集合中存储多种类型的对象,则需要在它们之间强制转换以访问特定于类型的成员,是的。

    如果您在一个集合中实际存储了一个派生类型的多个对象,那么应该改为使用泛型,以便集合保持强类型(即编译器知道集合只包含派生类型的实例)。

        3
  •  0
  •   Fredrik Mörk    17 年前

    我将添加一个示例:

    PrimitiveCollection primitives = GetPrimitives() ' this gets a mixture of types
    If GetType(PrimitiveRectangle) = primitives[0].GetType() Then
        ' this is a PrimitiveRectangle object
        PrimitiveRectangle rect = CType(primitives[0], PrimitiveRectangle)
        ' now you can access specialized members through rect
    End If