You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 11/.NET 4.8中SortedDictionary全球化问题原因咨询

问题原因分析:SortedDictionary在越南区域性下查找失败

问题场景

网站按用户当前区域性展示数据,越南用户访问时出现键找不到的异常,复现代码如下:

static void SortedDicProblem(Action<string> Write)
{
    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

    const string key = "KH";

    SortedDictionary<string, string> laCountries = new()
    {
        { key, "Kambodscha " },
        { "KI", "Kiribati " },
        { "KM", "Komoren " },
    };

    foreach (CultureInfo loCult in System.Globalization.CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures))
    {
        Test(loCult.Name);
    }

    void Test(string vsCulture)
    {
        Thread.CurrentThread.CurrentCulture = new CultureInfo(vsCulture);

        if (laCountries.TryGetValue(key, out string lsName))
        {
            Write($"{vsCulture}");
        }
        else
        {
            Write($"<span class='error'>{vsCulture}, Key not found: {key}, {Thread.CurrentThread.CurrentCulture.EnglishName}</span>");
        }
    }
}

错误原因

  • SortedDictionary<TKey, TValue> 默认使用**当前线程的区域性(CurrentCulture)**作为键的比较逻辑,也就是StringComparer.CurrentCulture。
  • 不同区域性的字符串比较规则存在差异:创建字典时用的是en-US区域性,键是按照英文排序规则存储的;但切换到越南(vi-VN)区域性后,TryGetValue会用越南语的比较规则去匹配键。
  • 在越南语的排序规则中,"KH"会被当作一个特殊的字符组合处理,和英文环境下的排序/匹配逻辑不一致,导致原本存在的键无法被找到。

解决方案

创建SortedDictionary时显式指定序数比较器(StringComparer.Ordinal),比较逻辑基于字符串的Unicode码点,完全不受区域性影响,确保所有环境下键的匹配逻辑一致:

new SortedDictionary<string, string>(StringComparer.Ordinal)

内容的提问来源于stack exchange,提问作者Christoph Wissing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 02:32:43