C# 如何制作一个面向对象的登录程序?
以下代码的问题是什么?我的代码给了我一些错误。我想在我们的项目中使用面向对象的程序,但它不能很好地工作。有人能帮我解决我的问题吗C# 如何制作一个面向对象的登录程序?,c#,oop,C#,Oop,以下代码的问题是什么?我的代码给了我一些错误。我想在我们的项目中使用面向对象的程序,但它不能很好地工作。有人能帮我解决我的问题吗 class Login { public string Username { get; set; } public string Userpassword { get; set; } public Login() { this.Username = user; //do
class Login
{
public string Username { get; set; }
public string Userpassword { get; set; }
public Login()
{
this.Username = user; //does not exist in the current context
this.Userpassword = pass; //does not exist in the current context
}
private void ClearTexts(string user, string pass)
{
user = String.Empty;
pass = String.Empty;
}
public void Login(string user, string pass)
{
int count = 0;
Connection connection = new Connection();
string sql = "SELECT * FROM tbl_Login";
MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand(sql, conn);
conn.Open();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Login Successfully!");
frmLogin.Hide(); //required for the non-static field,method
frmMain.showMe(this); //best overloaded method match...
}
else
{
txtPassword.Focus(); /does not exist in the current context
MessageBox.Show("Username or Password Is Incorrect");
txtUserName.Text = ""; //does not exist in the current context
txtPassword.Text = ""; //does not exist in the current context
}
connection.Close();
}
}
您不需要没有参数的
Login()
构造函数。而是使用如下参数将字段设置向下移动到构造函数:
public void Login(string user, string pass)
{
this.Username = user;
this.Userpassword = pass;
// more code here
}
user
和pass
不是函数的参数,因此它们不存在。您已经有了一个接受用户并传递的构造函数,因此该构造函数应该将其设置为null或不存在,并强制使用用户/传递构造函数Welcome!“我的代码给了我一些错误”。那不是很有帮助。请包括相关的细节,如什么错误和什么行,所以我们有一些想法在哪里寻找。您可以使用评论上方的“编辑”链接编辑问题,以添加此信息。对此表示抱歉。我对错误进行了注释。您分配用户名和密码的构造函数没有任何参数,这就是您可能会得到“在当前上下文中不存在”错误的原因。txtsername
和txtspassword
将永远不存在,因为您不定义它们。两个不同的类有两个不同的作用域txtUsername
可能在表单上,而这是一个单独的类,因此txtUsername
不在范围frmLogin.txtUsername.Text
中。从代码结构的角度来看,在这个单独的类中包含这么多的表单逻辑不是最好的,但这可能是以后您有更多经验时需要解决的问题。
public Login(){
this.Username = user; //does not exist in the current context
this.Userpassword = pass; //does not exist in the current context
}