我稍微弄乱了 C#,发现一段代码给出了非常不舒服的结果:
static void Main(string[] args)
{
string a = "string", b = "string\0";
bool b1 = a == b;
bool b2 = (a.CompareTo(b) > 0);
bool b3 = (a.CompareTo(b) < 0);
bool b4 = (a.CompareTo(b) == 0);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine("{0} {1} {2} {3}", b1, b2, b3, b4);
}
输出:
string
string
False False False True
预期输出(关于):
string
string
True False False True
最佳答案
CompareTo
的结果并不意味着相等,它与排序顺序有关。我不确定出于排序目的而忽略空字符是否太令人惊讶。
根据 the documentation :
Character sets include ignorable characters. The CompareTo(String) method does not consider such characters when it performs a culture-sensitive comparison.
关于C# 字符串 : why string a == b operator gives different answer than a. CompareTo(b) == 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38728101/