簡體   English   中英

檢測到C#無法訪問代碼

[英]C# Unreachable Code Detected

我已經整整一個多小時了。 即使閱讀Stackoverflow解決方案,我仍然不知道如何解決。 該程序使用第一個用戶名和密碼(測試和密碼),當我鍵入第二個用戶名和密碼(aaa和123)時,它不起作用。

public partial class Form2 : Form
{

    String[] username = { "test", "aaa" };
    String[] password = { "password", "123" };

private void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            for (int i = 0; i < username.Length; i++) // <------- Unreachable Code
            {
                if ((txtUsername.Text.Trim() == username[i]) && (txtPassword.Text.Trim() == password[i]))
                {
                    MessageBox.Show("Login Successful. Welcome!", "Login Success", MessageBoxButtons.OK, MessageBoxIcon.None);
                    Form3 frm3 = new Form3();
                    frm3.Visible = true;
                    frm3.Activate();
                    break;
                }
                else
                {
                    MessageBox.Show("You have entered an invalid input. Do you want to try again?", "Invalid Input", MessageBoxButtons.YesNo, MessageBoxIcon.Hand); break;
                }
            }
        }
        catch(Exception x)
        {
            MessageBox.Show("System Error! Please try again!", "System Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        }
    }
}

您在兩個if-else分支中都有break詞。 從其他地方刪除break 但是您會在每個循環中看到消息框。 因此,您需要修改代碼:將消息框移出循環。

您的代碼內部存在邏輯流控制問題。 結果,您需要將MessageBox觸發移動到循環之外。

如果修改代碼以使用列表而不是數組並包含一些LINQ,則可以完全擺脫循環,並且可以減少嵌套。

public partial class Form2 : Form
{
    List<string> username = new List<string>{ "test", "aaa" };
    List<string> password = new List<string>{ "password", "123" };

    private void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtUsername.Text.Length > 0 && txtPassword.Text.Length > 0 
                && username.Any(x => x == txtUsername.Text.Trim())
                && password.Any(x => x == txtPassword.Text.Trim()))
            {
                MessageBox.Show(
                    "Login Successful. Welcome!", 
                    "Login Success", MessageBoxButtons.OK, MessageBoxIcon.None);
                Form3 frm3 = new Form3();
                frm3.Visible = true;
                frm3.Activate();
            }
            else
            {
                MessageBox.Show(
                    "You have entered an invalid input. Do you want to try again?", 
                     "Invalid Input", 
                     MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
            }
        }
        catch(Exception x)
        {
            MessageBox.Show(
                "System Error! Please try again!", "System Error", 
                MessageBoxButtons.OK, MessageBoxIcon.Hand);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM