如何将字符串转换成版本在.NET 3.5中? [英] How to convert string into version in .net 3.5?

查看:139
本文介绍了如何将字符串转换成版本在.NET 3.5中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在3.5中创建的软件版本与旧一一比较。如果我尝试在4.0版本相比较,然后很容易通过使用 Version.Parse ,但在早期版本的工具是不存在的。我试图用字符串比较,但仍然没能得到需要的结果进行比较,因为字符串比较不允许我与次要版本或主要版本进行比较。先谢谢了。

I want to compare the software version created in 3.5 with the older one. If I try to compare version in 4.0 then it's easy by using Version.Parse but in earlier version this facility is not there. I tried to compare it by using string comparison but still not able get the desired output because string comparison doesn't allow to me compare with minor version or major version. Thanks in advance.

推荐答案

我遇到了类似的问题 - 我不得不分析和排序内部版本号,因此他们可能被显示为降序用户。最后我写我自己的类来包​​装的一个版本号的零件,并实现IComparable的排序。也结束了超载大于和小于操作员,以及在等于方法。我认为这是最的版本类的功能,除了MajorRevision和MinorRevision,这是我从来没有使用过。

I ran into a similar problem - I had to parse and sort build numbers so they could be displayed to the user in descending order. I ended up writing my own class to wrap the parts of a build number, and implemented IComparable for sorting. Also ended up overloading the greater than and less than operators, as well as the Equals method. I think it has most of the functionality of the Version class, except for MajorRevision and MinorRevision, which I never used.

其实,你很可能重新命名为版本,并用它完全像你的真实的类来完成。

In fact, you could probably rename it to 'Version' and use it exactly like you've done with the 'real' class.

这里的code:

public class BuildNumber : IComparable
{
    public int Major { get; private set; }
    public int Minor { get; private set; }
    public int Build { get; private set; }
    public int Revision { get; private set; }

    private BuildNumber() { }

    public static bool TryParse(string input, out BuildNumber buildNumber)
    {
        try
        {
            buildNumber = Parse(input);
            return true;
        }
        catch
        {
            buildNumber = null;
            return false;
        }
    }

    /// <summary>
    /// Parses a build number string into a BuildNumber class
    /// </summary>
    /// <param name="buildNumber">The build number string to parse</param>
    /// <returns>A new BuildNumber class set from the buildNumber string</returns>
    /// <exception cref="ArgumentException">Thrown if there are less than 2 or 
    /// more than 4 version parts to the build number</exception>
    /// <exception cref="FormatException">Thrown if string cannot be parsed 
    /// to a series of integers</exception>
    /// <exception cref="ArgumentOutOfRangeException">Thrown if any version 
    /// integer is less than zero</exception>
    public static BuildNumber Parse(string buildNumber)
    {
        if (buildNumber == null) throw new ArgumentNullException("buildNumber");

        var versions = buildNumber
            .Split(new[] {'.'},
                   StringSplitOptions.RemoveEmptyEntries)
            .Select(v => v.Trim())
            .ToList();

        if (versions.Count < 2)
        {
            throw new ArgumentException("BuildNumber string was too short");
        }

        if (versions.Count > 4)
        {
            throw new ArgumentException("BuildNumber string was too long");
        }

        return new BuildNumber
            {
                Major = ParseVersion(versions[0]),
                Minor = ParseVersion(versions[1]),
                Build = versions.Count > 2 ? ParseVersion(versions[2]) : -1,
                Revision = versions.Count > 3 ? ParseVersion(versions[3]) : -1
            };
    }

    private static int ParseVersion(string input)
    {
        int version;

        if (!int.TryParse(input, out version))
        {
            throw new FormatException(
                "buildNumber string was not in a correct format");
        }

        if (version < 0)
        {
            throw new ArgumentOutOfRangeException(
                "buildNumber",
                "Versions must be greater than or equal to zero");
        }

        return version;
    }

    public override string ToString()
    {
        return string.Format("{0}.{1}{2}{3}", Major, Minor, 
                             Build < 0 ? "" : "." + Build,
                             Revision < 0 ? "" : "." + Revision);
    }

    public int CompareTo(object obj)
    {
        if (obj == null) return 1;
        var buildNumber = obj as BuildNumber;
        if (buildNumber == null) return 1;
        if (ReferenceEquals(this, buildNumber)) return 0;

        return (Major == buildNumber.Major)
                   ? (Minor == buildNumber.Minor)
                         ? (Build == buildNumber.Build)
                               ? Revision.CompareTo(buildNumber.Revision)
                               : Build.CompareTo(buildNumber.Build)
                         : Minor.CompareTo(buildNumber.Minor)
                   : Major.CompareTo(buildNumber.Major);
    }

    public static bool operator >(BuildNumber first, BuildNumber second)
    {
        return (first.CompareTo(second) > 0);
    }

    public static bool operator <(BuildNumber first, BuildNumber second)
    {
        return (first.CompareTo(second) < 0);
    }

    public override bool Equals(object obj)
    {
        return (CompareTo(obj) == 0);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            var hash = 17;
            hash = hash * 23 + Major.GetHashCode();
            hash = hash * 23 + Minor.GetHashCode();
            hash = hash * 23 + Build.GetHashCode();
            hash = hash * 23 + Revision.GetHashCode();
            return hash;
        }
    }
}

这篇关于如何将字符串转换成版本在.NET 3.5中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆