当在c#中比较两个相等的字符串时,不变文化和序数比较之间有什么区别?


当前回答

这确实很重要,比如——有一种东西叫做角色扩展

var s1 = "Strasse";
var s2 = "Straße";

s1.Equals(s2, StringComparison.Ordinal);           //false
s1.Equals(s2, StringComparison.InvariantCulture);  //true

使用InvariantCulture, ß字符扩展为ss。

其他回答

总是尝试在那些接受它作为重载的字符串方法中使用InvariantCulture。通过使用InvariantCulture,你是安全的。许多。net程序员可能不会使用这个功能,但如果您的软件将被不同的区域性使用,那么InvariantCulture是一个非常方便的特性。

下面是一个例子,使用InvariantCultureIgnoreCase和OrdinalIgnoreCase进行字符串相等性比较将不会给出相同的结果:

string str = "\xC4"; //A with umlaut, Ä
string A = str.Normalize(NormalizationForm.FormC);
//Length is 1, this will contain the single A with umlaut character (Ä)
string B = str.Normalize(NormalizationForm.FormD);
//Length is 2, this will contain an uppercase A followed by an umlaut combining character
bool equals1 = A.Equals(B, StringComparison.OrdinalIgnoreCase);
bool equals2 = A.Equals(B, StringComparison.InvariantCultureIgnoreCase);

如果你运行这个,equals1将为假,而equals2将为真。

Another handy difference (in English where accents are uncommon) is that an InvariantCulture comparison compares the entire strings by case-insensitive first, and then if necessary (and requested) distinguishes by case after first comparing only on the distinct letters. (You can also do a case-insensitive comparison, of course, which won't distinguish by case.) Corrected: Accented letters are considered to be another flavor of the same letters and the string is compared first ignoring accents and then accounting for them if the general letters all match (much as with differing case except not ultimately ignored in a case-insensitive compare). This groups accented versions of the otherwise same word near each other instead of completely separate at the first accent difference. This is the sort order you would typically find in a dictionary, with capitalized words appearing right next to their lowercase equivalents, and accented letters being near the corresponding unaccented letter.

序数比较严格地比较数字字符值,在第一个差值处停止。这种方法将大写字母与小写字母完全分开排序(重音字母可能也与这些字母分开),因此大写单词的排序将与它们的小写对等物完全不同。

InvariantCulture还认为大写字母大于小写字母,而Ordinal认为大写字母小于小写字母(这是在计算机还没有小写字母之前遗留下来的ASCII,大写字母先分配,因此比后面添加的小写字母的值更低)。

例如,通过顺序:“0”<“9”<”“< <“Z”“Ab”<”“<“Ab”< <“Z”“Ab”<”“<“Ab”<”“<“Ab”

InvariantCulture:“0”<“9”<“a”<“A”<“á”<“Á”<“ab”<“aB”<“Ab”<“áb”<“Áb”<“Z”<

不需要使用花哨的unicode字符示例来显示差异。这是我今天发现的一个令人惊讶的简单例子,它只包含ASCII字符。

根据ASCII表,0 (48,0x30)在顺序比较时小于_ (95,0x5F)。InvariantCulture会说相反的(PowerShell代码如下):

PS> [System.StringComparer]::Ordinal.Compare("_", "0")
47
PS> [System.StringComparer]::InvariantCulture.Compare("_", "0")
-1

这确实很重要,比如——有一种东西叫做角色扩展

var s1 = "Strasse";
var s2 = "Straße";

s1.Equals(s2, StringComparison.Ordinal);           //false
s1.Equals(s2, StringComparison.InvariantCulture);  //true

使用InvariantCulture, ß字符扩展为ss。