gpt4 book ai didi

c# - .NET Framework 的字符串比较中的错误

转载 作者:IT王子 更新时间:2023-10-29 03:55:44 27 4
gpt4 key购买 nike

这是对任何 comparison sort 的要求工作,底层订单运算符是 transitive and antisymmetric .

在 .NET 中,某些字符串并非如此:

static void CompareBug()
{
string x = "\u002D\u30A2"; // or just "-ア" if charset allows
string y = "\u3042"; // or just "あ" if charset allows

Console.WriteLine(x.CompareTo(y)); // positive one
Console.WriteLine(y.CompareTo(x)); // positive one
Console.WriteLine(StringComparer.InvariantCulture.Compare(x, y)); // positive one
Console.WriteLine(StringComparer.InvariantCulture.Compare(y, x)); // positive one

var ja = StringComparer.Create(new CultureInfo("ja-JP", false), false);
Console.WriteLine(ja.Compare(x, y)); // positive one
Console.WriteLine(ja.Compare(y, x)); // positive one
}

你看到了x严格大于 y , 和 y严格大于 x .

因为 x.CompareTo(x)等等都给零(0),很明显这不是一个命令。毫不奇怪,当我 Sort 时,我得到了不可预测的结果。包含 x 等字符串的数组或列表和 y .虽然我还没有测试过,但我确定 SortedDictionary<string, WhatEver>如果像 x 这样的字符串,将无法保持自身的排序和/或定位项目和 y用于键。

这个错误是众所周知的吗?哪些版本的框架受到影响(我正在尝试使用 .NET 4.0)?

编辑:

下面是一个符号为负的例子:

x = "\u4E00\u30A0";         // equiv: "一゠"
y = "\u4E00\u002D\u0041"; // equiv: "一-A"

最佳答案

如果正确排序在您的问题中如此重要,只需使用序号 string comparison而不是文化敏感。只有这个才能保证你想要的传递性和反对称比较。

What MSDN says:

Specifying the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase value in a method call signifies a non-linguistic comparison in which the features of natural languages are ignored. Methods that are invoked with these StringComparison values base string operation decisions on simple byte comparisons instead of casing or equivalence tables that are parameterized by culture. In most cases, this approach best fits the intended interpretation of strings while making code faster and more reliable.

它按预期工作:

    Console.WriteLine(String.Compare(x, y, StringComparison.Ordinal));  // -12309
Console.WriteLine(String.Compare(y, x, StringComparison.Ordinal)); // 12309

是的,它不能解释为什么文化敏感比较会给出不一致的结果。好吧,奇怪的文化——奇怪的结果。

关于c# - .NET Framework 的字符串比较中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13254153/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com