Public Class Form1
Private firstClicked As Label = Nothing
Private secondClicked As Label = Nothing
Private random As New Random
Private icons =
New List(Of String) From {"!", "!", "N", "N", ",", ",", "k", "k", "b", "b", "v", "v", "w", "w", "z", "z"}
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
AssignIconsToSquares()
End Sub
Private Sub AssignIconsToSquares()
For Each Control In TableLayoutPanel1.Controls
Dim iconLabel = TryCast(Control, Label)
If iconLabel IsNot Nothing Then
Dim randomNumber = random.Next(icons.Count)
iconLabel.Text = icons(randomNumber)
iconLabel.ForeColor = iconLabel.BackColor
icons.RemoveAt(randomNumber)
End If
Next
End Sub
Private Sub label_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Click, Label9.Click, Label8.Click, Label7.Click, Label6.Click, Label5.Click, Label4.Click, Label3.Click, Label2.Click, Label16.Click, Label15.Click, Label14.Click, Label13.Click, Label12.Click, Label11.Click, Label10.Click, Label1.Click
If Timer1.Enabled Then Exit Sub
Dim clickedLabel1 = TryCast(sender, Label)
If clickedLabel1 IsNot Nothing Then
If clickedLabel1.ForeColor = Color.Black Then Exit Sub
If firstClicked Is Nothing Then
firstClicked = clickedLabel1
firstClicked.ForeColor = Color.Black
Timer1.Start()
Exit Sub
End If
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
firstClicked.ForeColor = firstClicked.BackColor
secondClicked.ForeColor = secondClicked.BackColor
firstClicked = Nothing
secondClicked = Nothing
End Sub
End Class
嗨,这是我按照这里的教程制作匹配游戏的代码: http://msdn.microsoft.com/en-us/library/vstudio/dd553235(v=vs.100).aspx
我的问题是我收到错误:
A first chance exception of type 'System.NullReferenceException'
occurred in Matching Game.exe
指向该行:
secondClicked.ForeColor = secondClicked.BackColor
有人可以帮助我吗?
答案 0 :(得分:1)
您尚未分配secondClicked
个实例:
' secondClicked is null (nothing)
Private secondClicked As Label = Nothing;
...
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
firstClicked.ForeColor = firstClicked.BackColor
' Trying to get BackColor and ForeColor of null (nothing)
secondClicked.ForeColor = secondClicked.BackColor
可能(很难肯定地说)你应该把它
firstClicked.ForeColor = firstClicked.BackColor
' if secondClicked can be assigned (not null) change its color
If secondClicked IsNot Nothing Then
secondClicked.ForeColor = secondClicked.BackColor
' second clicked became first clicked, and first clicked - nothing
secondClicked = firstClicked
firstClicked = Nothing