Difference between String.Compare and CultureInfo&

2019-08-03 03:48发布

问题:

I was trying my hand over System.Gloablization in a small desktop app. I am a bit confused about the additional control CultureInfo.Compare() has to offer than using String.Compare() method and its overloads.

Let's say I have two strings

String s1 = "\u3057\u3093\u304B\u3093\u305b\u3093"; //some Japanese text in Unicode
String s2 = "\u30b7\u3043\u30ab\u30f3\u30bb\u30f3"; //Some Japanese text in Unicode
CultureInfo ci = new CultureInfo("ja-JP");

String.Compare has several overloads, out of which currently I would use

String.Compare(String strA, String strB, CultureInfo culture, CompareOptions options)

(where CompareOptions is an Enumerated type)

However, I could also use:

CompareInfo compareInfo = CompareInfo.GetCompareInfo("ja-JP");
compareInfo.Compare(String strA, String strB, CompareOptions options);

for the same purpose.

How does the CultureInfo's CompareInfo object provide more control when handling such situation in globalization such as Japanese text for eg: CompareOptions.IgnoreKanaType (where Kana is a second form of Japanese which can be ignored from the string using CompareOptions enumaerated type).

回答1:

Yes Jon skeet is right, String.Compare internally calls CultureInfo.Compare method, here is the actual code from IL:

    public static int Compare(string strA, string strB, CultureInfo culture, CompareOptions options)
{
    if (culture == null)
    {
        throw new ArgumentNullException("culture");
    }
    return culture.CompareInfo.Compare(strA, strB, options);
}

The other thing to be noticed here is that, CultureInfo.Compare method internally does not check (at first) for input (culture) is null or not. It just directly does other operation. Also it does calls again string.Compare(string,string,StringOptions) API if OrdinalIgnoreCase is used. So best is to use String.Compare since there is a null checking before any operation is done.



回答2:

I believe String.Compare will simply delegate to the CompareInfo it's provided - it's just more convenient not to have to get hold of the CompareInfo yourself.

Given that they do the same thing, I'm not sure what your final question really means.