在StringComparison和StringComparer之间转换的优雅方法? [英] Elegant way of converting between StringComparison and StringComparer?

查看:52
本文介绍了在StringComparison和StringComparer之间转换的优雅方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些.NET方法使用 StringComparison 作为参数,有些使用 StringComparer (通常以

Some .NET methods use StringComparison as parameter, some use StringComparer (often in form of IComparer). The difference is clear. Is there some elegant way how to get StringComparison from StringComparer or vice versa?

我总是可以编写使用 Case 语句的简单方法,但是.NET中可能已经存在我忽略的东西.

I can always write simple method which uses Case statement, but perhaps there is already something present in .NET what I am overlooking.

推荐答案

StringComparison StringComparer 很简单-只需创建一个 Dictionary< StringComparison,StringComparer>; :

Going from StringComparison to StringComparer is simple - just create a Dictionary<StringComparison, StringComparer>:

var map = new Dictionary<StringComparison, StringComparer>
{
    { StringComparison.Ordinal, StringComparer.Ordinal },
    // etc
};

每个 StringComparison 值都有一个 StringComparer ,因此这种方式非常容易工作.请注意, StringComparer.CurrentCulture 取决于当前线程的区域性-因此,如果您填充字典,然后修改线程的区域性(或从具有不同区域性的不同线程中进行操作),您可能最终会错误的值.您可能需要 Dictionary< StringComparison,Func< StringComparer>> :

There is a StringComparer for every StringComparison value, so that way works really easily. Mind you, StringComparer.CurrentCulture depends on the current thread culture - so if you populate the dictionary and then modify the thread's culture (or do it from a different thread with a different culture) you may end up with the wrong value. You potentially want a Dictionary<StringComparison, Func<StringComparer>>:

var map = new Dictionary<StringComparison, Func<StringComparer>>
{
    { StringComparison.Ordinal, () => StringComparer.Ordinal },
    // etc
};

然后您可以通过调用委托随时获取比较器:

Then you can get a comparer at any time by invoking the delegate:

var comparer = map[comparison]();

采用另一种方法是不可行的,因为并非每个 StringComparer 都具有合适的 StringComparison .例如,假设我(在英国)为法语( StringComparer.Create(new CultureInfo(...,true)))创建了一个 StringComparer .代表什么吗?对于当前的文化,不变的文化或序数比较,这是不正确的.

Going the other way is infeasible, because not every StringComparer has a suitable StringComparison. For example, suppose I (in the UK) create a StringComparer for French (StringComparer.Create(new CultureInfo(..., true)). Which StringComparison does that represent? It's not correct for the current culture, the invariant culture, or ordinal comparisons.

这篇关于在StringComparison和StringComparer之间转换的优雅方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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