首页 > 解决方案 > 如何从用户输入将多个项目添加到字典中

问题描述

我是 C# 新手,我正在尝试使用用户输入在字典中添加多个元素。我尝试了不同的组合,但在测试程序时仍然只能看到 1 个条目。您可以在下面找到我的注册方法,它是 3 选项菜单的一部分。我将字典用作公共类并创建了一个属性,因此我可以在不同的方法中使用它。我不知道我的逻辑是否不正确,但我希望得到一些反馈。

private static void Register()
{
    userData = new Dictionary<string, string>();

    //input for user to add username and password 
    string userName = "";
    string password = "";

    SystemMessage("Enter a Username :");
    userName = Console.ReadLine();

    SystemMessage("Enter a Password :");
    password = Console.ReadLine();

    //add username and password in to dictionary
    userData.Add(userName, password);

    //check that username is not the same aas the password for better security
    if (userName.Equals(password))
    {
        ErrorMesssage("Username and Password cannot be the same");
    }

    if (userData.Equals(userName))
    {
        ErrorMesssage($"Username: {userName} already exist!");
    }
    else
    {
        //get count of key/value items
        Console.WriteLine(userData.Count);
    }
}

标签: c#dictionary

解决方案


一个快速的方法是让你的字典像一个静态的

private static Dictionary<string, string> userData = new Dictionary<string, string>();

在您当前的实现中,每次调用该Register方法时,您都会创建一个新Dictionary的当然是空的。

一般反馈

  1. 您以错误的顺序处理数据

        userData.Add(userName, password);
    
    
        //check that username is not the same aas the password for better security
        if (userName.Equals(password))
        {
            ErrorMesssage("Username and Password cannot be the same");
    
        }
    
        if (userData.Equals(userName))
        {
            ErrorMesssage($"Username: {userName} already exist!");
    
        }
    

您首先进行验证检查(用户名与密码和密钥相同),然后添加到 distionary。

  1. 为了检查您的字典中是否有条目,您不使用Equal方法,而是userData.ContainsKey(userName)

所以代码应该看起来像

    //check that username is not the same aas the password for better security
    if (userName.Equals(password, StringComparison.OrdinalIgnoreCase))
    {
        ErrorMesssage("Username and Password cannot be the same");
    }
    if (userData.ContainsKey(userName))
    {
        ErrorMesssage($"Username: {userName} already exist!");
    }
    else
    {
        //get count of key/value items
        Console.WriteLine(userData.Count);
    }
    userData.Add(userName, password);
  1. 因为它是一个密码,即使对于一个 uni 项目,至少使用一些散列可能是个好主意,所以在你将它保存在某个地方之前它不是平面测试

推荐阅读