For 循环中的中断(有一些问题)

问题描述 投票:0回答:1

所以我目前在 C# 中使用 EPPLUS,试图从 Excel 文件中获取一些数据。它正在工作,但是,中断;让我的头“轰隆隆”。我的 for 循环中有一些片段,如果我放置了中断;或者摆脱它,阻止我的程序通过并冻结它。所以我被困在这一段代码中,它只是冻结了我的应用程序。你能帮我一下吗? (请不要叫我傻瓜或类似的东西,我正在学习)

for (int row = 2; row <= end.Row;)
{ // Row by row...
    for (int col = start.Column; col <= end.Column; col++)
    { // ... Cell by cell...
        string cellValue = ws.Cells[row, col].Text;

        if (String.Compare(cellValue, "Номер Машины", true) == 0)
        {
            for (int row_ = row + 1; row_ <= end.Row;)
            {
                for (int col_ = col; col_ <= end.Column;)
                {
                    string cellValue_ = ws.Cells[row_, col_].Text;
                    MessageBox.Show(cellValue_);


                    for (int row__ = row_ + 1; row__ <= end.Row;)
                    {
                        for (int col__ = col_; col__ <= end.Column;)
                        {
                            string cellValue__ = ws.Cells[row__, col__].Text;
                            if (cellValue__ != string.Empty)
                            {
                                MessageBox.Show(cellValue__);
                                break;
                            }
                            
                        }
                        break;
                    }
                    break;
                }
                break;
            }
            
        }
    }
    break;
}

我正在玩“break;”但这只是让一切变得更糟,感谢上帝我有备份

c# for-loop break
1个回答
0
投票

这些中断立即退出当前循环。因此,所有这些外循环只会循环一次。您无法使用中断从最里面的循环退出所有循环。

这是使用

goto
语句有意义的罕见情况:

// (Code simplified)
for (int row_ = row + 1; row_ <= end.Row;) {
    for (int col_ = col; col_ <= end.Column;) {
        for (int row__ = row_ + 1; row__ <= end.Row;) {
            for (int col__ = col_; col__ <= end.Column;) {
                if (cellValue__ != string.Empty) {
                    MessageBox.Show(cellValue__);
                    goto exit_all;
                }
            }
        }
    }
}
exit_all:

如果你想从最内层循环返回结果,你可以将此代码放入方法或本地函数中:

// (Code simplified)
string GetResult()
{
    for (int row_ = row + 1; row_ <= end.Row;) {
        for (int col_ = col; col_ <= end.Column;) {
            for (int row__ = row_ + 1; row__ <= end.Row;) {
                for (int col__ = col_; col__ <= end.Column;) {
                    if (cellValue__ != string.Empty) {
                        return cellValue__;
                    }
                }
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.