c# - 如何从用户输入将多个项目添加到字典中
问题描述
我是 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);
}
}
解决方案
一个快速的方法是让你的字典像一个静态的
private static Dictionary<string, string> userData = new Dictionary<string, string>();
在您当前的实现中,每次调用该Register
方法时,您都会创建一个新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!"); }
您首先进行验证检查(用户名与密码和密钥相同),然后添加到 distionary。
- 为了检查您的字典中是否有条目,您不使用
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);
- 因为它是一个密码,即使对于一个 uni 项目,至少使用一些散列可能是个好主意,所以在你将它保存在某个地方之前它不是平面测试
推荐阅读
- discord - 自定义服务器前缀错误 discord.py bot
- .net - 真正微不足道的 WPF 绑定拒绝工作
- javascript - 如何将javascript添加到php中?
- python - 多尺度模板匹配与文本检测
- r - 在R中,当字符串长度可变时,如何分隔字符串的开始、中间和结尾?
- angular - 赛普拉斯无法获得 Angular 选择的选定值
- node.js - 如何使用 discord.js 执行“报告错误”命令
- unit-testing - 普罗米修斯:“for”打破了我的考验
- sql - 我收到此错误“无法绑定多部分标识符“DCOT.Loyalty”。”
- google-cloud-platform - GCP 默认服务帐户和自定义服务帐户有什么显着区别?