C# 无法转换类型错误,但两种类型相同?
C# 无法转换类型错误,但两种类型相同?,c#,C#,publicstaticdictionary userList=newdictionary(); 这就是在另一个类中声明“userList”的方式。顺便说一句,该类的名称是“User”,与类型相同,这可能会导致问题,但我不确定。我不知道如何诚实地完成这项工作 以下是完整的脚本: 脚本中的一些东西还没有意义,因为我从另一个脚本中复制了一些东西 但基本上我是在检查静态字典中是否已经存在昵称,如果已经存在,则通知用户,不要做任何其他事情。user.userList是一个字典。如果对其进行迭代,则每个
publicstaticdictionary userList=newdictionary();
这就是在另一个类中声明“userList”的方式。顺便说一句,该类的名称是“User”,与类型相同,这可能会导致问题,但我不确定。我不知道如何诚实地完成这项工作
以下是完整的脚本:
脚本中的一些东西还没有意义,因为我从另一个脚本中复制了一些东西
但基本上我是在检查静态字典中是否已经存在昵称,如果已经存在,则通知用户,不要做任何其他事情。
user.userList
是一个字典。如果对其进行迭代,则每个元素都是一个用户,而不是用户
因此,您可以:
foreach (KeyValuePair<string, User> kvp in User.userList)
{
User user = kvp.Value;
}
如果字典中每个用户的键是用户的昵称,那么您根本不需要循环。您的代码:
foreach (User u in User.userList)
{
string uN = u.GetNickName();
if (name == uN)
{
builder.WithTitle("A practice with the name you specified already exists!");
goto EndFunction;
}
}
EndFunction:
await ReplyAsync("", false, builder.Build());
可替换为:
if (User.userList.ContainsKey(name))
{
builder.WithTitle("A practice with the name you specified already exists!");
}
await ReplyAsync("", false, builder.Build());
如果没有,您仍然可以使用linq简化此代码:
最后,不建议以这种方式使用goto
。只需使用break代码>对于未来的读者,解决这些问题的一个提示是查看错误消息。这里写着:
无法将KeyValuePair
转换为User
这仅仅意味着预期的强制转换是KeyValuePair
,而不是用户
因此,如果将循环中的User
替换为KeyValuePair
,则代码可以工作 字典里的键是什么?如果它们是昵称,您可以查找密钥。否则,您可以使用foreach(User.userList.Values中的User u)
迭代所有用户。回答得好,我非常感激。我对字典的使用不是很有经验,也不知道那个方法的存在,我也不知怎么地忘记了打破它,所以再次感谢。
foreach (User u in User.userList)
{
string uN = u.GetNickName();
if (name == uN)
{
builder.WithTitle("A practice with the name you specified already exists!");
goto EndFunction;
}
}
EndFunction:
await ReplyAsync("", false, builder.Build());
if (User.userList.ContainsKey(name))
{
builder.WithTitle("A practice with the name you specified already exists!");
}
await ReplyAsync("", false, builder.Build());
if (User.userList.Values.Any(x => x.GetNickName() == name))
{
builder.WithTitle("A practice with the name you specified already exists!");
}
await ReplyAsync("", false, builder.Build());