2010-05-12 140 views
1

也許我只是不知道要搜索什麼,但是我在這裏試着弄清楚如何創建一個繼承類的集合。基類,我永遠不會使用。無法創建繼承類的集合

基本上,我有3個分量:通過它創建一個 收集和循環

  1. 甲基類呼叫的imageformat ImageForm
  2. 代碼中的Sub Main()的
  3. 子類來循環。

所以它這樣做,#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型或instantied單身模式 - 將不勝感激您對此有任何想法)

然後,我的例程是:

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

的三個屬性:

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 
+0

完美!謝謝! – 2010-05-12 07:04:31

1

那麼,你的_name等是Shared,這意味着他們是類級別的變量。當你添加WindowsEnhancedMetafile時,它恰好用WMF特定信息覆蓋這些字段。如果您將您的代碼更改爲:

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

您將擁有「Windows位圖」打印三次。

所有你需要做的是改變你的字段聲明

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

非常好,謝謝安東。很好的解釋。邁克爾先入爲主,但也是+1。 – 2010-05-12 07:05:31