[英].NET IComparer sort error
我最近遇到了一個很奇怪的問題。 我部署了程序的新版本,並在內部調用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; }
}
}
是否還有其他人遇到過此問題並找到了解決方案? 我的比較器看起來是否涵蓋所有情況? 我完全不知道這個問題,也不知道下一步該怎么做。 任何幫助將不勝感激。
這個
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 ((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;
}
附帶說明一下,您編寫此比較器函數的方式效率很低。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.