【问题标题】:Cannot convert type error, but both types are the same? [duplicate]无法转换类型错误,但两种类型都相同? [复制]
【发布时间】:2020-04-24 22:31:44
【问题描述】:

public static Dictionary<string, User> userList = new Dictionary<string, User>();

这就是在另一个类中声明“userList”的方式。顺便说一句,该类的名称是“用户”,与类型相同,这可能会导致问题,但我不确定。我不知道如何诚实地完成这项工作。

这是完整的脚本:https://pastebin.com/h56ukpgR 脚本中的某些内容还没有意义,因为我从另一个脚本中复制了一些内容。

但基本上我正在尝试检查静态字典中是否已经存在昵称,如果存在则通知用户并且不要做任何其他事情。

【问题讨论】:

  • 字典中的键是什么?如果它们是昵称,您可以查找密钥。否则,您可以使用 foreach(User u in User.userList.Values) 迭代所有用户。

标签: c#


【解决方案1】:

User.userListDictionary&lt;string, User&gt;。如果你遍历它,每个元素都是KeyValuePair&lt;string, User&gt;,而不是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; 即可跳出循环。

【讨论】:

    【解决方案2】:

    对于未来的读者,解决这些问题的提示是查看错​​误消息。这里说:

    无法将KeyValuePair&lt;string, User&gt; 转换为User

    这仅仅意味着预期的演员表是KeyValuePair&lt;string, User&gt;,而不是User

    因此,如果您将循环中的User 替换为KeyValuePair&lt;string, User&gt;,您的代码将起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 2018-12-28
      • 1970-01-01
      • 2015-12-04
      • 2019-03-20
      • 1970-01-01
      • 2019-10-12
      相关资源
      最近更新 更多