User.userList 是 Dictionary<string, User>。如果你遍历它,每个元素都是KeyValuePair<string, User>,而不是User。
所以你可以这样做:
foreach (KeyValuePair<string, User> kvp in User.userList)
{
User user = kvp.Value;
}
或者你可以直接遍历dictionary's values:
foreach (User user in user.userList.Values)
{
}
如果字典中每个User 的键是用户的昵称,那么您根本不需要循环。你的代码:
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 的 Any 简化此代码:
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());
最后,不推荐这样使用goto。您只需使用break; 即可跳出循环。