如何基于另一个函数中断一个函数中的 for 循环

问题描述

我有一个名为 RunGame方法,它包含一组图块。然后我有一个 foreach 循环,它调用一个名为 CheckValid方法,该方法传入瓷砖编号和游戏编号。当 checkvalid 被调用时,它会检查数据库中的一个字段,看它是否为空。我想要做的是让 foreach 语句在找到不为空的字段时停止运行。这是我目前拥有的:

public void RunGame()
{
    try
    {
        int[,] game = new int[10,1] { { 70 },{ 71 },{ 62 },{ 14 },{ 12 },{ 41 },{ 19 },{ 71 } };
        int num = 2;

        foreach (int i in game)
        {
            CheckValid(i,num);
        }
        Console.ReadLine();
    }
    catch (Exception error)
    {
        Console.WriteLine(error);
        Console.ReadLine();
    }
}

public void CheckValid(int tile,int game)
{
    using (MysqLCommand cmd = new MysqLCommand("CheckValid",Conn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("tileVal",tile);
        cmd.Parameters.AddWithValue("num",game);
        Conn.open();
        
        using (MysqLDataReader read = cmd.ExecuteReader())
        {
            while (read.Read())
            {
                if (read[0] != dbnull.Value)
                {
                    Console.WriteLine($"This tile is occupied");
                }
                else
                {
                    Console.WriteLine($"Tile {tile} is not occupied");
                }
            }
            read.Close();
        }
        Conn.Close();
    }
}

我希望它根据这个 if 语句的条件运行:

if (read[0] != dbnull.Value)
{
    Console.WriteLine($"This tile is occupied");
    //Stop the foreach loop
}
else
{
    Console.WriteLine($"Tile {tile} is not occupied");
    //Continue the foreach loop
}

目前,它会在 71 块被占用时打印:

Tile 70 is not occupied
This tile is occupied //I would like it to stop before it prints this line
Tile 62 is not occupied
Tile 14 is not occupied
This tile is occupied
Tile 12 is not occupied
Tile 12 is not occupied
Tile 41 is not occupied
Tile 19 is not occupied
This tile is occupied

有可能实现吗?

解决方法

您可以编写这样的方法来返回 bool (true/false) 值:

public bool CheckValid(int tile,int game)
{
    using (MySqlCommand cmd = new MySqlCommand("CheckValid",Conn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("tileVal",tile);
        cmd.Parameters.AddWithValue("num",game);
        Conn.Open();
        using (MySqlDataReader read = cmd.ExecuteReader())
        {
            while (read.Read())
            {
                if (read[0] != DBNull.Value)
                {
                    Console.WriteLine($"This tile is occupied");
                    return false;
                }
                else
                {
                    Console.WriteLine($"Tile {tile} is not occupied");
                    return true;
                }
            }
            read.Close();
        }
        Conn.Close();
    }
    return false;
}

然后像这样更改其他代码以检查CheckValid的结果:

if (!CheckValid(i,num))
{
    break;
}

因此,您可以使用布尔结果来确定是否应该继续执行循环。

请注意,我已经修改了 CheckValid,如果没有数据,它将返回 false(意味着循环将 break;)。如果您想反其道而行之,请将 return false; 更改为 return true;