-4

嗨,我想制作一个登录屏幕,用户将在其中输入用户名和密码。但是如何使用数组验证它?请帮忙谢谢

        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");
        }
4

2 回答 2

0

你为什么不用字典?字典是某种数组,但它结合了匹配的键和值。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");
}
于 2013-05-08T06:23:27.903 回答
0

您需要首先从您的数组中找到用户名的索引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");
}
于 2013-05-08T05:05:16.417 回答