對不起,如果標題不是很清楚。這是一個VB.NET(2010)問題子類/超類 - 如果一個子類被轉換爲其超類,是否有一種方法可以使用子類的重載屬性?
我有一個叫做「設備」的超類,它有許多繼承它的子類。其中一些子類也有子類。特別是,我有一個名爲「TwinCatIntegerDevice」的類,它繼承了繼承「Device」的「TwinCatDevice」。
設備看起來像這樣的相關部分:
Public Class Device
Private _Setpoints As New List(Of Double)
Public Overridable Property Setpoints As List(Of Double)
Get
Return _Setpoints
End Get
Set(ByVal value As List(Of Double))
_Setpoints = value
_SetpointsTb.Clear()
For Each setpoint In value
Dim setpointTb As New TextBox
setpointTb.Text = setpoint.ToString
_SetpointsTb.Add(setpointTb)
Next
End Set
End Property
Private _SetpointsTb As New List(Of TextBox)
Public Overridable Property SetpointsTb As List(Of TextBox)
Get
Return _SetpointsTb
End Get
Set(ByVal value As List(Of TextBox))
_SetpointsTb = value
Me._Setpoints.Clear()
For Each setpoint In value
Me._Setpoints.Add(setpoint.Text)
Next
End Set
End Property
End Class
的TwinCatDevice類不超載設定值或SetpointsTb。 的TwinCatIntegerDevice類做:
Public Class TwinCatIntegerDevice
Inherits TwinCatDevice
Private _Setpoints As New List(Of Integer)
Public Overloads Property Setpoints As List(Of Integer)
Get
Return _Setpoints
End Get
Set(ByVal value As List(Of Integer))
_Setpoints = value
_SetpointsTb.Clear()
For Each setpoint In value
Dim setpointTb As New TextBox
setpointTb.Text = setpoint.ToString
_SetpointsTb.Add(setpointTb)
Next
End Set
End Property
Private _SetpointsTb As New List(Of TextBox)
Public Overloads Property SetpointsTb As List(Of TextBox)
Get
Return _SetpointsTb
End Get
Set(ByVal value As List(Of TextBox))
_SetpointsTb = value
Me._Setpoints.Clear()
For Each setpoint In value
Me._Setpoints.Add(setpoint.Text)
Next
End Set
End Property
End Class
現在的問題。我嘗試使用像這樣的子程序設置設定值:
Private Sub FetchDeviceRecipe(ByRef device As Device, ByRef excelSheet As ExcelWorksheet, ByVal row As Integer)
Dim lastCol As Integer = NumberOfProcessSteps + 1
Try
For col = 2 To lastCol
Dim setpoint As New TextBox
setpoint.Text = excelSheet.Cells(row, col).Value
device.SetpointsTb.Add(setpoint)
Next
device.SetpointsTb = device.SetpointsTb
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
(我知道這是可怕的代碼:X,我是一個初學者)
重要的是,我傳遞的設備作爲設備超類(這樣我就不必爲每個子類型有一個單獨的子例程)。
當我做了一個名爲「ThisDevice」已經傳遞給子程序後TwinCatIntegerDevice:
MsgBox("As Device: " & CType(ThisDevice, Device).Setpoints.Count.ToString & vbNewLine & _
"As TwinCatDevice: " & CType(ThisDevice, TwinCatDevice).Setpoints.Count.ToString & vbNewLine & _
"As TwinCatIntegerDevice: " & CType(ThisDevice, TwinCatIntegerDevice).Setpoints.Count.ToString)
我得到以下(9在這種情況下設定值的正確的號碼):
As Device: 9
As TwinCatDevice: 9
As TwinCatIntegerDevice: 0
有沒有人知道爲什麼TwinCatInteger設備類顯然有一個不同的設定點變量,當它被轉換爲它的超類設備?
對不起,如果這看起來有點不一致。任何幫助將是偉大的!即使在形式或其他方面。我仍然試圖把這整個VB.NET的事情弄清楚。
是的,我之前有過。我認爲這個問題是,當我將我們的子類對象強制轉換爲超類時,它不會將值分配給陰影屬性。這是不正確的? – 2010-09-14 23:16:24