String.Compare和CultureInfo的CompareInfo之间的区别 [英] Difference between String.Compare and CultureInfo's CompareInfo

查看:107
本文介绍了String.Compare和CultureInfo的CompareInfo之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个小型桌面应用程序中移交System.Gloabisation。我对使用 CultureInfo.Compare()提供的附加控件而不是使用 String.Compare()感到困惑方法及其重载。

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.

假设我有两个字符串

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 有一些重载其中我目前将使用

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

String.Compare(String strA,String strB,CultureInfo文化,CompareOptions选项)

(其中CompareOptions是枚举类型)

(where CompareOptions is an Enumerated type)

但是,我也可以使用:

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

出于相同的目的。

如何在处理全球化中的这种情况(例如日语文本)时,CultureInfo的CompareInfo对象是否提供了更多控制,例如:CompareOptions.IgnoreKanaType(其中,假名是日语的第二种形式,可以使用CompareOptions枚举类型从字符串中忽略掉)。

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).

推荐答案

是的,Jon skeet是正确的,String.Compare内部调用CultureInfo.Compare方法,这是来自IL的实际代码:

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);
}

这里要注意的另一件事是,CultureInfo.Compare方法在内部执行首先不检查输入(区域性)是否为空。它只是直接执行其他操作。如果使用OrdinalIgnoreCase,它也会再次调用string.Compare(string,string,StringOptions)API。
最好使用String.Compare,因为在执行任何操作之前都会进行null检查。

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.

这篇关于String.Compare和CultureInfo的CompareInfo之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆