无法创建继承类的集合

时间:2010-05-12 06:43:56

标签: vb.net class inheritance collections

也许我只是不知道要搜索什么,但我在这里试图弄清楚如何创建一个继承类的集合。基类,我永远不会使用。

基本上,我有3个组件:

  1. 基类调用ImageFormat
  2. ImageForm的子类
  3. Sub Main()中的代码循环创建一个 收集并循环通过它。
  4. 所以它做到了,#3。问题是它总是将最后一项添加到集合中并仅使用它的值。

    这是我的基类:

    Public MustInherit Class ImageFormat
        Protected Shared _extentions As String()
        Protected Shared _targettype As String
        Protected Shared _name As String
    
        Public ReadOnly Property Extentions As String()
            Get
                Return _extentions
            End Get
        End Property
        Public ReadOnly Property TargetType As String
            Get
                Return _targettype
            End Get
        End Property
        Public ReadOnly Property Name As String
            Get
                Return _name
            End Get
        End Property
    End Class
    

    以下是儿童班:

    Class WindowsEnhancedMetafile
        Inherits ImageFormat
        Sub New()
            _extentions = {"EMF"}
            _targettype = "jpg"
            _name = "Windows Enhanced Metafile"
        End Sub
    End Class
    Class WindowsBitmap
        Inherits ImageFormat
        Sub New()
            _extentions = {"BMP", "DIB", "RLE", "BMZ"}
            _targettype = "jpg"
            _name = "Windows Bitmap"
        End Sub
    End Class
    Class WindowsMetafile
        Inherits ImageFormat
        Sub New()
            _extentions = {"WMF"}
            _targettype = "jpg"
            _name = "Windows Metafile"
        End Sub
    End Class
    

    (不知道这些子类是否需要不同,比如只是从ImageFormat类型或Singleton模式中即时显示 - 会对你对此有任何想法表示赞赏)

    然后,我的例行程序是:

    Sub Main()
        Dim imgFormats As New List(Of ImageFormat)
        imgFormats.Add(New WindowsBitmap)
        imgFormats.Add(New WindowsMetafile)
        imgFormats.Add(New WindowsEnhancedMetafile)
        Dim name As String = String.Empty
        For Each imgFormat In imgFormats
            name = imgFormat.Name
            Console.WriteLine(name)
        Next
        Console.ReadLine()
    End Sub
    

    这会在控制台上返回 Windows增强型图元文件三次。我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

三个属性:

Protected Shared _extentions As String()
Protected Shared _targettype As String
Protected Shared _name As String

被标记为共享 - 它们属于类而不是对象。

每次为_name指定一个新值时,它会覆盖旧值,因此每次都会打印相同的名称。

应该是:

Protected _extentions As String()
Protected _targettype As String
Protected _name As String

答案 1 :(得分:1)

嗯,你的_name等人是Shared,这意味着他们是班级变量。当您添加WindowsEnhancedMetafile时,它恰好用WMF特定信息覆盖这些字段。如果您将代码更改为:

imgFormats.Add(New WindowsMetafile)
imgFormats.Add(New WindowsEnhancedMetafile)
imgFormats.Add(New WindowsBitmap)

你会有三次打印“Windows Bitmap”。

您所要做的就是将字段声明更改为

Protected _extentions As  String()
Protected _targettype As String
Protected _name As String
相关问题