如何检查前一个标签是否与数组中的某些值具有相同的值

How to check if previous label has the same value as something in an array

我正在尝试创建一个“快照!”游戏。我正在尝试检查标签的先前文本是否对应于标签的当前文本,例如如果标签的前一个文本是 bee,而当前显示是 bee,它将显示 'Snap!'.

到目前为止,这是我的代码:

Private Sub btnOne_Click(sender As Object, e As EventArgs) Handles btnOne.Click
        Dim imageResourceNames = {"Owl", "Bee", "Bird", "Frog", "Duck"}
        Dim randImage As New Random
        Dim index = randImage.Next(imageResourceNames.Length)
        Dim imageResourceName = imageResourceNames(index)
        Dim img = DirectCast(My.Resources.ResourceManager.GetObject(imageResourceName), Image)

        picOne.Image = img
        picOne.Visible = True
        lblDisplay.Text = imageResourceNames(Index)
        btnOne.Enabled = False

        If lblDisplay.Text = imageResourceName Then
            Console.WriteLine("snap!")
            lblDisplay.Text = "Snap!"
        End If

    End Sub

虽然我没有收到错误,但标签似乎总是显示 'Snap!'。如果有人知道如何解决这个问题,我将不胜感激!

谢谢,

您将 imageResourceNamelblDisplay.Text 设置为相同的值 imageResourceNames(index)。所以当你那么你的 if lblDisplay.Text = imageResourceName 总是会被执行。


您没有显示足够的代码来给出关于如何使其工作的明确答案,但像这样的东西很接近:

Private CurrentImageResourceName As String = String.Empty

Private Sub btnOne_Click(sender As Object, e As EventArgs) Handles btnOne.Click
    Dim imageResourceNames = {"Owl", "Bee", "Bird", "Frog", "Duck"}
    Dim randImage As New Random
    Dim index = randImage.Next(imageResourceNames.Length)
    Dim imageResourceName = imageResourceNames(index)
    Dim img = DirectCast(My.Resources.ResourceManager.GetObject(imageResourceName), Image)

    picOne.Image = img
    picOne.Visible = True
    btnOne.Enabled = False

    If CurrentImageResourceName = imageResourceName Then
        Console.WriteLine("snap!")
        lblDisplay.Text = "Snap!"
    End If
    
    CurrentImageResourceName = imageResourceName
End Sub

您需要重构它以使其按您想要的方式工作。

A Label 不是数据存储,因此请停止将其视为数据存储。它只是向用户显示文本。如果您想知道之前的值是什么,请将其存储在一个变量中。

Private previousImageResourceName As String
Private currentImageResourceName As String
Private randImage As New Random

和:

Dim imageResourceNames = {"Owl", "Bee", "Bird", "Frog", "Duck"}
Dim index = randImage.Next(imageResourceNames.Length)

previousImageResourceName = currentImageResourceName
currentImageResourceName = imageResourceNames(index)

Dim img = DirectCast(My.Resources.ResourceManager.GetObject(imageResourceName), Image)

picOne.Image = img
picOne.Visible = True
lblDisplay.Text = currentImageResourceName
btnOne.Enabled = False

If currentImageResourceName = previousImageResourceName Then
    Console.WriteLine("snap!")
    lblDisplay.Text = "Snap!"
End If