假设我有两个字符串:a 和 b。为了比较在忽略大小写的情况下 a 和 b 是否具有相同的值,我一直使用以下方法:
// (Assume a and b have been verified not to be null)
if (a.ToLower() == b.ToLower())
但是,使用Reflector,我在.NET Framework中见过这样的情况:
// (arg three is ignoreCase)
if (string.Compare(a, b, true) == 0)
我测试了一下哪种方法更快,发现在我使用的字符串中,ToLower()
比Compare()
每次都要快。
那么,为什么要使用Compare()
而不是ToLower()
呢?是因为CultureInfo
的差异吗?我很困惑。
NullReferenceException
而不是错误的结果。因为你不能将“无”与“有”进行比较。在极少数情况下,如果null
是有意义的,我会事先检查是否为null
并返回false
,而不是用一个用于替换Equals
的 compare 函数来代替它,从而使代码变得晦涩难懂。 - Maarten Bodewes