1

我正在制作 ac# 登录系统,与 MySQL 连接,目前进展顺利。我怎样才能使这段代码更好?它的代码太多了。

if (string.IsNullOrEmpty(textBoxUsername.Text))
{
    //Focus box before showing a message
    textBoxUsername.Focus();
    MessageBox.Show("Enter your username", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
    //Focus again afterwards, sometimes people double click message boxes and select another control accidentally
    textBoxUsername.Focus();
    return;
}
else if (string.IsNullOrEmpty(textBoxPassword.Text))
{
    textBoxPassword.Focus();
    MessageBox.Show("Enter your password", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
    textBoxPassword.Focus();
    return;
}
4

2 回答 2

0

您可以简单地将其作为通用逻辑移动并重用代码,如下所示。

       private bool IsValidateTextBoxSuccess(TextBox textBox, string messageString)
        {
            if (string.IsNullOrEmpty(textBox.Text.Trim()))
            {
                MessageBox.Show(messageString, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                textBox.Focus();
                return false;
            }
            else
            {
                return true;
            }
        }

只是这样调用:

 bool isValidateSuccess = IsValidateTextBoxSuccess(textBoxUsername, "Enter your username") ?  IsValidateTextBoxSuccess(textBoxPassword, "Enter your password") :false ;

    if(isValidateSuccess)
    {
    // Then check with the database with entered credential is valid or not 
    }
    else
    return;
于 2013-11-13T19:32:24.913 回答
0

您可以创建一个私有函数,例如:

private bool isValidTextBox(TextBox box, string message)
{
    if(string.IsNullOrEmpty(box.Text))
    {                
        MessageBox.Show(message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); 
        box.Focus();
        return false;
    }
    return true;
}

然后,使用该功能,如:

if(!isValidTextBox(textBoxUsername, "Enter your username"))
     return;
else if(!isValidTextBox(textBoxPassword, "Enter your password"))
     return;
于 2013-11-13T19:09:51.533 回答