这是我的代码,它采用“1、5、0、4”或“1.5.0.4”形式的两个版本标识符,并确定哪个是较新的版本。
请提出建议或改进!
/// <summary>
/// Compares two specified version strings and returns an integer that
/// indicates their relationship to one another in the sort order.
/// </summary>
/// <param name="strA">the first version</param>
/// <param name="strB">the second version</param>
/// <returns>less than zero if strA is less than strB, equal to zero if
/// strA equals strB, and greater than zero if strA is greater than strB</returns>
public static int CompareVersions(string strA, string strB)
{
char[] splitTokens = new char[] {'.', ','};
string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);
string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);
int[] versionA = new int[4];
int[] versionB = new int[4];
for (int i = 0; i < 4; i++)
{
versionA[i] = Convert.ToInt32(strAsplit[i]);
versionB[i] = Convert.ToInt32(strBsplit[i]);
}
// now that we have parsed the input strings, compare them
return RecursiveCompareArrays(versionA, versionB, 0);
}
/// <summary>
/// Recursive function for comparing arrays, 0-index is highest priority
/// </summary>
private static int RecursiveCompareArrays(int[] versionA, int[] versionB, int idx)
{
if (versionA[idx] < versionB[idx])
return -1;
else if (versionA[idx] > versionB[idx])
return 1;
else
{
Debug.Assert(versionA[idx] == versionB[idx]);
if (idx == versionA.Length - 1)
return 0;
else
return RecursiveCompareArrays(versionA, versionB, idx + 1);
}
}
@达伦·科普:
版本类不处理格式 1.0.0.5 的版本。