通常最好使用哪种-StringComparison.OrdinalIgnoreCase或者StringComparison.InvariantCultureIgnoreCase?

时间:2020-03-05 18:56:03  来源:igfitidea点击:

我有一些这样的代码:

If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then
    DoSomething()
End If

我不在乎这个案子。我应该使用" OrdinalIgnoreCase"," InvariantCultureIgnoreCase"还是" CurrentCultureIgnoreCase"吗?

解决方案

回答

这取决于我们想要什么,尽管我会回避不变文化,除非我们非常确定我们永远都不想本地化其他语言的代码。请改用CurrentCulture。

另外,OrdinalIgnoreCase应该尊重数字,这可能是我们想要的,也可能不是。

回答

MSDN对此提出了一些非常明确的建议:http://msdn.microsoft.com/zh-cn/library/ms973919.aspx

回答

来自MSDN的"在Microsoft .NET 2.0中使用字符串的新建议"

Summary: Code owners previously using the InvariantCulture for string comparison, casing, and sorting should strongly consider using a new set of String overloads in Microsoft .NET 2.0. Specifically, data that is designed to be culture-agnostic and linguistically irrelevant should begin specifying overloads using either the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase members of the new StringComparison enumeration. These enforce a byte-by-byte comparison similar to strcmp that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance. (15 printed pages)

回答

我想这取决于情况。由于顺序比较实际上是在查看字符的数字Unicode值,因此当我们按字母顺序排序时,它们并不是最佳选择。但是,对于字符串比较,序数会更快一些。