如何将字符串转换为.net 3.5中的版本

本文关键字:版本 net 字符串 转换 | 更新日期: 2023-09-27 18:28:05

我想将3.5中创建的软件版本与旧版本进行比较。如果我尝试比较4.0中的版本,那么使用Version.Parse很容易,但在早期版本中没有这个功能。我试图通过字符串比较来进行比较,但仍然无法获得所需的输出,因为字符串比较不允许我与次要版本或主要版本进行比较。提前谢谢。

如何将字符串转换为.net 3.5中的版本

如果我遗漏了什么,请原谅,但你不能使用传递版本字符串的版本对象构造函数:

http://msdn.microsoft.com/en-us/library/y0hf9t2e%28v=vs.90%29.aspx?cs-保存lang=1&cs lang=csharp#code-snippet-1

string str = "0.1.2.3";
Version v = new Version(str);

这存在于以下.NET框架中:

4.8、4.7.2、4.7.1、4.7、4.6.2、4.6.1、4.6、4.5.2、4.5.1、4.5、4.0、3.5、3.0、2.0、1.1

我遇到了一个类似的问题——我必须解析和排序构建号,以便它们可以按降序显示给用户。最后,我编写了自己的类来包装内部版本号的各个部分,并实现了用于排序的IComparable。最后还重载了大于和小于运算符,以及Equals方法。我认为它拥有Version类的大部分功能,除了MajorRevision和MinorRevision,我从未使用过它们。

事实上,您可能会将它重命名为"Version",并像使用"real"类一样使用它。

这是代码:

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 4.0版本类-您可能很幸运,它只适用于.NET 3.5。

否则,您应该研究字符串拆分或正则表达式。

您似乎在询问如何获取任何本地.NET安装的版本。MSDN有一篇关于此的文章:http://msdn.microsoft.com/en-us/library/hh925568%28v=vs.110%29.aspx.

其中包括以下功能:

private static void GetVersionFromRegistry()
{
     // Opens the registry key for the .NET Framework entry. 
        using (RegistryKey ndpKey = 
            RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").
            OpenSubKey(@"SOFTWARE'Microsoft'NET Framework Setup'NDP'"))
        {
            // As an alternative, if you know the computers you will query are running .NET Framework 4.5  
            // or later, you can use: 
            // using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,  
            // RegistryView.Registry32).OpenSubKey(@"SOFTWARE'Microsoft'NET Framework Setup'NDP'"))
        foreach (string versionKeyName in ndpKey.GetSubKeyNames())
        {
            if (versionKeyName.StartsWith("v"))
            {
                RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
                string name = (string)versionKey.GetValue("Version", "");
                string sp = versionKey.GetValue("SP", "").ToString();
                string install = versionKey.GetValue("Install", "").ToString();
                if (install == "") //no install info, must be later.
                    Console.WriteLine(versionKeyName + "  " + name);
                else
                {
                    if (sp != "" && install == "1")
                    {
                         Console.WriteLine(versionKeyName + "  " + name + "  SP" + sp);
                    }
                }
                if (name != "")
                {
                    continue;
                }
                foreach (string subKeyName in versionKey.GetSubKeyNames())
                {
                    RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
                    name = (string)subKey.GetValue("Version", "");
                    if (name != "")
                        sp = subKey.GetValue("SP", "").ToString();
                    install = subKey.GetValue("Install", "").ToString();
                    if (install == "") //no install info, must be later.
                        Console.WriteLine(versionKeyName + "  " + name);
                    else
                    {
                        if (sp != "" && install == "1")
                        {
                            Console.WriteLine("  " + subKeyName + "  " + name + "  SP" + sp);
                        }
                        else if (install == "1")
                        {
                            Console.WriteLine("  " + subKeyName + "  " + name);
                        }
                    }
                }
            }
        }
    }
}