这就是我想要做的事情:
private void btnOk_Click(object sender, EventArgs e)
{
string login = loginTextBox.Text;
string password = passwordtextBox.Text;
myLogin m = new myLogin(login, password);
**if (m.getX != "" && m.getY != "")**
{
displayLabel.Text = "The information entered is:";
resultLogin.Text =
"Login: " + m.getX();
resultPassword.Text =
"Password: " + m.getY();
} // end if
else
displayLabel.Text = "Enter information above";
} // end method OkButton_Click
问题在于代码被" **"包围。有没有办法检查文本框是否为空而没有收到错误?
编辑:
myLogin看起来像这样:
public class myLogin
{
private readonly string login, password;
public myLogin(string x, string y)
{
login = x;
password = y;
}
public string getX()
{
return login;
}
public string getY()
{
return password;
}
答案 0 :(得分:1)
您希望调用方法并比较其结果:
if (m.getX() != "" && m.getY() != "") ...
作为进一步改进,您可能希望将方法重构为属性:
//TODO: think on changing name "X" to "Login"
public string X {
get {
return login;
}
}
//TODO: think on changing name "X" to "Password"
public string Y {
get {
return password;
}
}
完成此操作后,您可以轻松完成
if (X != "" && Y != "") ...
最后,只需将登录/密码验证的所有逻辑移到自己的类中:
// This class holds login/password: so it's it that responsible for validation
public class MyLogin() {
public MyLogin(string login, string password) {
if (null == login)
throw new ArgumentNullException("login");
else if (null == password)
throw new ArgumentNullException("password");
Login = login;
Password = password;
}
// Property with a readble name (what's X?)
public string Login {
get;
private set;
}
// Property with a readble name (what's Y?)
public string Password {
get;
private set;
}
public bool IsValid {
get {
return !string.IsNullOrEmpty(Login) &&
!string.IsNullOrEmpty(Password);
}
}
}
请注意现在如何轻松工作:
private void btnOk_Click(object sender, EventArgs e) {
MyLogin m = new myLogin(loginTextBox.Text, passwordtextBox.Text);
if (m.IsValid)
{
displayLabel.Text = "The information entered is:";
resultLogin.Text = $"Login: {m.Login}";
resultPassword.Text = $"Password: {m.Password}";
}
else
displayLabel.Text = "Enter information above";
}