System.Version.Parse 方法

方法描述

将版本号的字符串表示形式转换为等效的 Version 对象。

语法定义(C# System.Version.Parse 方法 的用法)

public static Version Parse(
	string input
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
input System-String 包含要转换的版本号的字符串。
返回值 System.Version 一个等效于 input 参数中指定的版本号的对象。

提示和注释

input 参数必须采用以下格式:

复制

major.minor[.build[.revision]]

其中,主、次、内部和修订分别是版本号的四个组件“主版本号、次版本号、内部版本号和修订号”的字符串表示形式。 可选组件显示在方括号([ 和 ])中: 这些组分必须按指定顺序显示,并且必须用句点分隔。

重要事项

由于版本号的字符串表示形式必须符合可识别的模式,因此在调用 Parse 方法分析用户输入时,应用程序始终应使用异常处理。 或者,可以调用 TryParse 方法来分析版本号的字符串表示并返回一个指示分析操作是否成功的值。

Parse 方法是一个便利方法,等效于调用 Version(String) 构造函数。

System.Version.Parse 方法例子

下面的示例使用 Parse 方法来解析一组包含版本信息的字符串。

using System;

public class Example
{
   public static void Main()
   {
      string input = "4.0";
      ParseVersion(input);

      input = "4.0.";
      ParseVersion(input);

      input = "1.1.2";
      ParseVersion(input);

      input = "1.1.2.01702";
      ParseVersion(input);

      input = "1.1.2.0702.119";
      ParseVersion(input);

      input =  "1.3.5.2150000000";
      ParseVersion(input);
   }

   private static void ParseVersion(string input)
   {
      try {
         Version ver = Version.Parse(input);
         Console.WriteLine("Converted '{0} to {1}.", input, ver);
      }
      catch (ArgumentNullException) {
         Console.WriteLine("Error: String to be parsed is null.");
      }
      catch (ArgumentOutOfRangeException) {
         Console.WriteLine("Error: Negative value in '{0}'.", input);
      }
      catch (ArgumentException) {
         Console.WriteLine("Error: Bad number of components in '{0}'.", 
                           input);
      }
      catch (FormatException) {
         Console.WriteLine("Error: Non-integer value in '{0}'.", input);
      }
      catch (OverflowException) {   
         Console.WriteLine("Error: Number out of range in '{0}'.", input);                  
      }   
   }
}
// The example displays the following output:
//       Converted '4.0 to 4.0.
//       Error: Non-integer value in '4.0.'.
//       Converted '1.1.2 to 1.1.2.
//       Converted '1.1.2.01702 to 1.1.2.1702.
//       Error: Bad number of components in '1.1.2.0702.119'.
//       Error: Number out of range in '1.3.5.2150000000'.

异常

异常 异常描述
ArgumentNullException input 为 null。
ArgumentException input 少于两个组件或多于四个版本组件。
ArgumentOutOfRangeException 在 input 中至少有一个组件小于零。
FormatException 在 input 中至少有一个组件不是整数。
OverflowException input 中至少有一个组件表示大于 Int32.MaxValue 的数。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4 .NET Framework Client Profile 受以下版本支持:4

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。