c# - 比较版本标识符

标签 c# .net compare versions

这是我的代码,它采用“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);
        }
    }

@ Darren Kopp :

版本类不处理格式 1.0.0.5 的版本。

最佳答案

使用 Version类。

Version a = new Version("1.0.0.0");
Version b = new Version("2.0.0.0");

Console.WriteLine(string.Format("Newer: {0}", (a > b) ? "a" : "b"));
// prints b

关于c# - 比较版本标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494/

相关文章:

c# - 捕获没有焦点的击键

c# - 如何获取对象具有的属性数?

php - Mysql 比较两个 group_concat 结果

c++ - 用于匹配和计数的字符串和 int 的容器?

c# - 带或不带 .ToString() 的字符串连接?

c# - 选中 WPF 复选框时触发事件

c# - 注册免费 COM - 隔离 COM 引用 - 缺少值 '(Default)'

java - 如何比较 Java 中的路径等价性?

c# - 属性如何继承?

c# - 将泛型方法中的类型转换为不同的类型以进行内部泛型方法调用