简体   繁体   中英

Should I use '==' for .NET localized string comparisons?

What are the reasons not to use "==" to compare localized strings in .NET? How would the comparison execute in regards to the CultureInfo if I do use it?

If you compare culture-aware strings with ==, for example "Strasse" with "Straße", it returns false.

If you need culture-aware comparings for UI stuff (Sorting of Listview), you use String.Compare with the related CultureInfo.

CultureInfo ci = new CultureInfo("de-DE");
String.Compare("Strasse", "Straße", true, ci) // Returns zero

== is culture-insensitive - it's a simple ordinal comparison. So two strings which are culturally equal - or even equal in terms of other canonicalization forms - may not be equal via == . It basically treats each string like a char array.

The overloaded String.operator == will perform an culture-unaware ordinal comparison – it compares the strings byte-by-byte using a heavily optimized unrolled loop .
It calls the same internal function as String.Equals(a, b, StringComparison.Ordinal)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM