【问题标题】:c# weird Dictionary ContainsKey or StringComaprerc# 奇怪的 Dictionary ContainsKey 或 StringComaprer
【发布时间】:2016-07-12 08:08:53
【问题描述】:

这是一种奇怪的魔法, ContainsKey 返回 false。我尝试使用具有相同结果的 InvariantCulture 比较器。

GameCommands = new Dictionary<string, GameCommand>(StringComparer.Ordinal)
            {
                {"Start new game with deck", StartGame},
                {"​Tell color", TellColor},
                {"​Tell rank", TellRank},
                {"​Drop card", Drop},
                {"​Play card", Play},
            };
Debug.WriteLine(GameCommands.ContainsKey("Tell color"));

错误

我通过删除键中的引号并再次键入它们来解决它。我想知道为什么会这样。

【问题讨论】:

    标签: c# string dictionary containskey stringcomparer


    【解决方案1】:

    在某些字符串的开头有零宽度空格 (U+200B)。例如,复制这个:

    {"​Drop card", Drop},
    

    进入Unicode Explorer here,您会看到如下内容:

    现在,我们不知道那个字符来自哪里,但我怀疑你是从其他地方复制和粘贴文本。

    请注意,字典、string 或此处 .NET 中的任何内容的行为没有任何问题...只是您的源代码中存在问题。如果您更清楚地表达相同的字符串,您会看到完全相同的行为:

    {"\u200BDrop card", Drop},
    

    【讨论】:

    • {"\u2008Drop card", Drop}, ----> {"\u200BDrop card", Drop}, 看着你的桌子
    • @FelixCastor:哇!谢谢,已修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多