调用一个新的类问题...窗体 [英] calling a new class problem... windows form
问题描述
class usrpass
{
string User;
string Pass;
public usrpass(string User, string Pass)
{
this.User = User;
this.pass = Pass;
}
public string user
{
set { User = value;}
get{return User;}
}
public string pass
{
set { Pass = value; }
get { return Pass; }
}
public void Rslt()
{
string res1 = "";
string res2 = "";
using (StreamReader read = new StreamReader(@"D:\proj\password\New folder\pass.txt;"))
{
res1 = read.ReadLine();
res2 = read.ReadLine();
}
if (res1==user && res2==pass)
{
Question: (what should i put here ??
so that i can call this class to the main
and messagebox.show("Login success") it)
}
else
{
Question: (what should i put here ??
so that i can call this class to the main
and messagebox.show("pass incorrect") it)
}
}
--- -------------------------------------------------- ---------------
Main
--------------------------------------------------------------------
Main
private void button1_Click(object sender, EventArgs e)
{
resu();
textBox1.Clear();
textBox2.Clear();
}
public void resu()
{
usrpass usrpwd = new usrpass(textBox1.Text, textBox2.Text);
usrpwd.Rslt();
}
推荐答案
从方法返回布尔值成功与否
return boolean value as success or not from the method
public bool Rslt()
{
string res1 = "";
string res2 = "";
using (StreamReader read = new StreamReader(@"D:\proj\password\New folder\pass.txt"))
{
res1 = read.ReadLine();
res2 = read.ReadLine();
}
return (res1==user && res2==pass);
}
然后在主方法中
then in the main method
usrpass usrpwd = new usrpass(textBox1.Text, textBox2.Text);
if(usrpwd.Rslt())
{
//MessageBox.show("Login success");
}else
{
//MessageBox.show("pass incorrect");
}
一个非常简单的解决方法是将usrpwd.Rslt()方法从void转换为字符串。
One very simple fix is to turn your usrpwd.Rslt() method from a void, to a string.
public void Rslt()
变为
public string Rslt()
让你的方法返回字符串,然后让表单的resu()方法显示消息框。您的类是密码验证程序,而不是用户界面的一部分。您将用户交互的责任保留在旨在与用户交互的类中,即表单。
更多问题 - >看起来您的密码数据库只是一个未加密的文本文件?如果此代码构成任何企业级应用程序的一部分,则需要一个正确的密码认证机制:至少应对密码进行一些加密,最好是对可接受的安全标准(不是MD5)进行散列。 />
编辑:我喜欢 DamithSL 的解决方案更好,如果你只想显示一个消息框,那么你的类变得非常简单他们认证了布尔值。
Have your method return the string, and let the form's resu() method do the messagebox showing. Your class is a password validator and not a piece of the user interface. You keep the responsibility for User interaction inside a class that's designed to interact with the user i.e. the form.
More of an issue though -> it looks like your password database is just an unencrypted text file? If this code is to form part of any enterprise-level application it's going to need a proper password authentication mechanism: At the very least there should be some encryption on the passwords, preferably hashing to an acceptably secure standard (not MD5).
edit: I like DamithSL's solution better, if you only want to show a messagebox then your class becomes a really simple "did they authenticate" boolean.
这篇关于调用一个新的类问题...窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!