c# – 关于字符串比较的奇怪之处
作者:互联网
这段代码:
Console.WriteLine("~".CompareTo("a") > 0);
Console.WriteLine('~'.CompareTo('a') > 0);
给我:
False
True
WTF?
解决方法:
显示此行为的另一种方法是:
Console.WriteLine("a".CompareTo("b")); // -1
Console.WriteLine("b".CompareTo("a")); // 1
Console.WriteLine('a'.CompareTo('b')); // -1
Console.WriteLine('b'.CompareTo('a')); // 1
Console.WriteLine("~".CompareTo("a")); // -1
Console.WriteLine("a".CompareTo("~")); // 1
Console.WriteLine('~'.CompareTo('a')); // 29
Console.WriteLine('a'.CompareTo('~')); // -29
差异可能很微妙,但它是documented.Char.CompareTo(Char)中的比较是
based on
the encoded values of this instance
and value, not their lexicographical
characteristics.
同时,documentation for String.CompareTo(String)
performs a word (case-sensitive and
culture-sensitive) comparison using
the current culture.
即第一个基于订单的比较,后者基于当前文化中的默认规则(您可能在字典中看到的顺序).
标签:c,net,net-3-5,net-4-0 来源: https://codeday.me/bug/20190713/1451937.html