我正在编写一个序列猜测游戏,我想对它进行编程,这样每当你输入一个错误的数字时,它就会重置所有的标签,我如何通用地选择标签类型并使文本= Nothing
我尝试过this,但它不起作用
谢谢
Imports System.Media
Public Class comboForm
Dim score As Integer = 0
Dim winsound As New SoundPlayer(My.Resources.winsound_wav)
' 1 7 8 8 4 7 1 5 5
Private Sub btn1_Click(sender As Object, e As EventArgs) Handles btn1.Click
If score = 0 Then
score += 1
lblStage1.Text = "1"
ElseIf score = 7 Then
score += 1
lblStage7.Text = "7"
Else
score = 0
For Each lbl In tlpMain.Controls.OfType(Of Label)()
lbl.Text = Nothing
Next
End If
End Sub
End Class
发布于 2018-08-07 07:42:51
For Each lbl In Me.Controls.OfType(Of Label)()
'...
Next
OfType
方法基本上是一个列表上的按类型过滤。这段代码相当于下面的代码:
For Each ctrl In Me.Controls
If TypeOf ctrl Is Label Then
Dim lbl = DirectCast(ctrl, Label)
'...
End If
Next
或者这样:
For Each ctrl In Me.Controls
Dim lbl = TryCast(ctrl, Label)
If lbl IsNot Nothing Then
'...
End If
Next
显然,这段代码只能直接访问表单上的Labels
,因为它使用表单的Controls
集合。使用适当容器的Controls
集合,例如Panel
来访问该容器中的控件。
https://stackoverflow.com/questions/51716951
复制相似问题