gpt4 book ai didi

c# - 我在控制台应用程序中创建了一个类,现在我想创建一个使用该类的 Windows 窗体应用程序

转载 作者:太空宇宙 更新时间:2023-11-03 23:27:47 29 4
gpt4 key购买 nike

我创建了一个名为“验证”的按钮和两个文本框,以便程序可以获得一些用户输入。单击验证按钮时,我希望程序根据用户名和密码是否匹配返回“已验证”或“未验证”。有人知道这样做的方法吗? C# 新手,谢谢。我添加了下面的类以供引用。

class Authenticator
{
static void Main(string[] args)
{
Authenticator au = new Authenticator();
au.InitialValues();
if (au.Authenticate())
Console.WriteLine("Authenticated");
else
Console.WriteLine("NOT Authenticated");
Console.WriteLine("Press Enter to end");
Console.ReadLine();
}

private Dictionary<string, string> dictionary = new Dictionary<string, string>();

public void InitialValues()
{
dictionary.Add("username1", "password1");
dictionary.Add("username2", "password2");
dictionary.Add("username3", "password3");
dictionary.Add("username4", "password4");
dictionary.Add("username5", "password5");
}

public bool Authenticate()
{
bool authenticated = false;

Console.WriteLine("Please enter a username");
string inputUsername = Console.ReadLine();

Console.WriteLine("Please enter your password");
string inputPassword = Console.ReadLine();

if (dictionary.ContainsKey(inputUsername) && dictionary[inputUsername] == inputPassword)
{
authenticated = true;
}
else
{
authenticated = false;
}

return authenticated;
}
}

最佳答案

您可以只在Windows 窗体项目(exe-File)中引用控制台项目。这不是一个好的做法。最好将您重用的代码放在一个 Library 项目中,该项目将被 Console 和 Forms 项目引用。

请注意,如果没有控制台,您的代码将无法在 Forms 项目中运行。

添加类库项目howto:

在您的解决方案中创建一个新项目(右键单击“添加”->“新建项目”)并选择“类库”。在此之后,您右键单击您的控制台或表单项目并选择添加-> 引用。在对话框中转到项目引用并检查新创建的类库。现在将除 Main 函数之外的类复制到类库项目中并编译。请注意您重命名了您的项目。

要使身份验证有效,您应该使用参数而不是 Console.ReadLine。

在类库中

public class Authentication
{
private Dictionary<string, string> dictionary = new Dictionary<string, string>();

public Authentication()
{
dictionary.Add("username1", "password1");
dictionary.Add("username2", "password2");
dictionary.Add("username3", "password3");
dictionary.Add("username4", "password4");
dictionary.Add("username5", "password5");
}

public bool Authenticate(string user, string password)
{
// note i just replaced the variable with return
return dictionary.ContainsKey(user) && dictionary[user] == password;
}
}

在您的控制台应用程序中

Main(...)
{
// ...
Console.WriteLine("Please enter a username");
var user = Console.ReadLine();

Console.WriteLine("Please enter your password");
var password = Console.ReadLine();

var auth = new Authentication();

if(auth.Authenticate(user, password))
{ // do what you need to do ;) }
}

请注意,您的身份验证机制并不安全。所以不要在安全性非常重要的地方使用它。

关于c# - 我在控制台应用程序中创建了一个类,现在我想创建一个使用该类的 Windows 窗体应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33302336/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com