我正在VB.net(VS2017)中使用基类Button创建一个名为CDeviceButton的新类。然后,CDeviceButton将成为其他类(例如CMotorButton,CValveButton)的基础。
我想在子类CMotorButton中设置Tag属性,但要在CDeviceButton的构造函数中访问它。对我不起作用。原来是空的。
将CMotorButtom实例插入表单时,在标准属性中设置Tag。
我还试图通过将mybase.New()设置为每个构造函数中的第一个动作来确保父类的构造函数得以运行,但这没有任何改变。
有什么改进建议吗?
Public Class CDeviceButton
Inherits Button
Public MMIControl As String = "MMIC"
Public Sub New()
MMIControl = "MMIC" & Tag
End Sub
End class
Public Class CMotorButton
Inherits CDeviceButton
Sub New()
'Do Something
end Sub
End Class
答案 0 :(得分:0)
当您尝试将Tag与字符串连接时,您试图添加的对象可能什么都不是。我首先设置了Tag属性,并使用了.ToString,它似乎可以正常工作。
Public Class MyButton
Inherits Button
Public Property MyCustomTag As String
Public Sub New()
'Using an existing Property of Button
Tag = "My Message"
'Using a property you have added to the class
MyCustomTag = "Message from MyCustomTag property : " & Tag.ToString
End Sub
End Class
Public Class MyInheritedButton
Inherits MyButton
Public Sub New()
If CStr(Tag) = "My Message" Then
Debug.Print("Accessed Tag property from MyInheritedButton")
Debug.Print(MyCustomTag)
End If
End Sub
End Class
然后在表单中
Private Sub Test()
Dim aButton As New MyInheritedButton
MessageBox.Show(aButton.Tag.ToString)
MessageBox.Show(aButton.MyCustomTag)
End Sub
答案 1 :(得分:0)
以下是我提出的解决方案。基本上,我确保在读取Tag属性之前已进行所有初始化。我的经验是,即使在Form中创建CMotorButton实例时已设置Tag属性,在CMotorButton中的New()完成之前,Tag属性为空。 TimerInitate的滴答时间为500毫秒。
这不是最专业的解决方案,但可以满足我目前的需求。
另一个选择可能是多线程,但我没有尝试过,可以留给以后试用。
Public Class CDeviceButton
Inherits Button
Public MMIControl As String = "MMIC"
Public Sub New()
TimerInitiate = New Timer(Me)
End Sub
Private Sub TimerInitiate_Tick(sender As Object, e As EventArgs) Handles TimerInitiate.Tick
If Tag <> Nothing Then
TimerInitiate.Stop()
MMIControl = "MMIC" & Tag
End If
End Sub
End class
Public Class CMotorButton
Inherits CDeviceButton
Sub New()
'Do Some stuff
TimerInitiate.Start()
End Sub
Private Sub CMotorButton_Click(sender As Object, e As EventArgs) Handles Me.Click
End Class