在登录屏幕的if语句中检测到无法访问的代码?

时间:2016-04-14 18:31:33

标签: c#

public void Login()
    {

        //Admin login temp
        if (txtusername.Text == "admin" && txtpassword.Text == "admin123")
        {
            Form mainmenu = new frmmainmenu();
            Useraccounts.LoggedInUsername = txtusername.Text;
            this.Hide();
            mainmenu.Show();
            return;

错误在这里用户帐户显示为无法访问的代码,具有详细说明6个用户帐户的用户帐户类和LoggedInUsername变量

            //Make new object of useraccounts class for logging in
            **Useraccounts** Loginattempt = new Useraccounts();


            //Retrieve the number of accounts there are to run the loop the appropriate number of times
            int NoOfAccounts = Loginattempt.Username.Length;

            for (int i = 0; i <= NoOfAccounts; i++)
            {
                try
                {
                    //Checking the username against the class & check if password matches
                    if (txtusername.Text == Loginattempt.Username[i])
                    {
                        if (txtpassword.Text == Loginattempt.Password[i])
                        {
                            Form Mainmenu = new frmmainmenu();
                            Useraccounts.LoggedInUsername = txtusername.Text;
                            this.Hide();
                            Mainmenu.Show();
                            return;
                        }
                    }
                }
                catch
                {
                    //If the username cannot be found do nothing.
                }
            }

            {
                MessageBox.Show("Incorrect username or password.");
            }
        }
    }
}

}

2 个答案:

答案 0 :(得分:1)

你不需要在这里尝试捕获,因为如果返回成功执行,执行将不会继续。只是在返回后抛出一个错误,如果返回没有工作将执行

答案 1 :(得分:0)

Return 

表示停止执行函数并返回给定值。 由于您运行的是方法,因此不需要return

public void Login()
    {
    //Admin login temp
    if (txtusername.Text == "admin" && txtpassword.Text == "admin123")
    {
        Form mainmenu = new frmmainmenu();
        Useraccounts.LoggedInUsername = txtusername.Text;
        this.Hide();
        mainmenu.Show();
        return; <----**delete this return**