如何使用数组验证用户名和密码
本文关键字:密码 用户 验证 何使用 数组 | 更新日期: 2023-09-27 18:12:28
嗨,我想做一个登录屏幕,其中用户将输入用户名和密码。但是我如何使用数组验证它?请帮忙,谢谢
int[] username = { 807301, 992032, 123144 ,123432};
string[] password = {"Miami", "LosAngeles" ,"NewYork" ,"Dallas"};
if (username[0].ToString() == password[0])
{
MessageBox.Show("equal");
}
else
{
MessageBox.Show("not equal");
}
首先需要从数组username
中找到用户名的索引。然后基于该索引比较密码数组中的密码。
int[] username = { 807301, 992032, 123144, 123432 };
string[] password = { "Miami", "LosAngeles", "NewYork", "Dallas" };
int enteredUserName = 123144;
string enteredPassword = "NewYork";
//find the index from the username array
var indexResult = username.Select((r, i) => new { Value = r, Index = i })
.FirstOrDefault(r => r.Value == enteredUserName);
if (indexResult == null)
{
Console.WriteLine("Invalid user name");
return;
}
int indexOfUserName = indexResult.Index;
//Compare the password from that index.
if (indexOfUserName < password.Length && password[indexOfUserName] == enteredPassword)
{
Console.WriteLine("User authenticated");
}
else
{
Console.WriteLine("Invalid password");
}
你为什么不用字典呢?字典是某种数组,但它结合了匹配的键和值。TryGetValue
将尝试查找用户名。如果没有找到用户名,则返回false
,否则返回true
和匹配的密码。此密码可用于验证用户输入的密码。
Dictionary<int, string> userCredentials = new Dictionary<int, string>
{
{807301, "Miami"},
{992032, "LosAngeles"},
{123144, "NewYork"},
{123432 , "Dallas"},
};
int userName = ...;
string password = ...;
string foundPassword;
if (userCredentials.TryGetValue(userName, out foundPassword) && (foundPassword == password))
{
Console.WriteLine("User authenticated");
}
else
{
Console.WriteLine("Invalid password");
}