【发布时间】:2015-09-15 19:03:13
【问题描述】:
我最近遇到了一个非常奇怪的问题。我部署了一个新版本的程序,并在内部调用 IComparer.Compare() 方法时收到此错误:
Unable to sort because the IComparer.Compare0 method returns inconsistent
results. Either a value does not compare equal to itself, or one value repeatedly
compared to another value yields different results. x:",x's type: 'String',
IComparer.".
奇怪的是,我无法在我的计算机上重现此问题。我在 Visual Studio 2013(调试或发布版本)中不会发生这种情况,安装应用程序时也不会发生这种情况。更奇怪的是,它甚至不会发生在生产中的每台计算机上,只有大约 30%。
我的应用程序面向 .NET Framework 4,平台目标是 x86。
我的代码中只有一个 IComparer 对象的实例,这里是:
public int Compare(string stringOne, string stringTwo)
{
if (stringOne == stringTwo) { return 0; }
else if (stringOne == null) { return stringTwo == null ? 0 : -1; }
else if (stringTwo == null) { return stringOne == null ? 0 : 1; }
else if (stringOne.StartsWith("_") && !stringTwo.StartsWith("_"))
{
return -1;
}
else if (!stringOne.StartsWith("_") && stringTwo.StartsWith("_"))
{
return 1;
}
else if ((stringOne.StartsWith("l") || stringOne.StartsWith("L")) &&
(!stringTwo.StartsWith("l") || !stringTwo.StartsWith("L")))
{
return -1;
}
else if ((!stringOne.StartsWith("l") || !stringOne.StartsWith("L")) &&
(stringTwo.StartsWith("l") || stringTwo.StartsWith("L")))
{
return 1;
}
else
{
if (stringTwo == null) { return 1; }
else { return stringOne.CompareTo(stringTwo) == 1 ? -1 : 1; }
}
}
有没有其他人遇到过这个问题并找到了解决方案?我的比较器看起来是否涵盖了所有情况?我完全迷失了这个问题,不知道下一步该尝试什么。任何帮助将不胜感激。
【问题讨论】:
-
你能把追踪放进去看看值是什么吗?失败了?
-
这并不能直接帮助您解决问题,但请查看
String.StartsWith(String, StringComparison)。那么你就不需要检查l和L。
标签: c# .net sorting compare icomparer