Int32.TryParse 方法 
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将数字的字符串表示形式转换为其等效的 32 位有符号整数。 返回值指示操作是否成功。
重载
| TryParse(String, IFormatProvider, Int32) | 尝试将字符串分析为值。 | 
| TryParse(ReadOnlySpan<Char>, Int32) | 将区域性特定格式的数字的跨度表示形式转换为其等效的 32 位带符号整数。 返回值指示转换是否成功。 | 
| TryParse(String, Int32) | 将数字的字符串表示形式转换为其等效的 32 位有符号整数。 返回值指示转换是否成功。 | 
| TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32) | 尝试将 UTF-8 字符的范围分析为值。 | 
| TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32) | 尝试将字符范围分析为值。 | 
| TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32) | 尝试将 UTF-8 字符的范围分析为值。 | 
| TryParse(ReadOnlySpan<Byte>, Int32) | 尝试将包含数字字符串表示形式的 UTF-8 字符范围转换为其等效的 32 位带符号整数。 | 
| TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32) | 将指定样式和区域性特定格式的数字的跨度表示形式转换为其等效的 32 位有符号整数。 返回值指示转换是否成功。 | 
| TryParse(String, NumberStyles, IFormatProvider, Int32) | 将指定样式和区域性特定格式的数字的字符串表示形式转换为其等效的 32 位带符号整数。 返回值指示转换是否成功。 | 
TryParse(String, IFormatProvider, Int32)
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
尝试将字符串分析为值。
public:
 static bool TryParse(System::String ^ s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IParsable<int>::TryParse;public static bool TryParse(string? s, IFormatProvider? provider, out int result);static member TryParse : string * IFormatProvider * int -> boolPublic Shared Function TryParse (s As String, provider As IFormatProvider, ByRef result As Integer) As Boolean参数
- s
- String
要分析的字符串。
- provider
- IFormatProvider
一个对象,提供有关 s的区域性特定格式设置信息。
- result
- Int32
此方法返回时,包含成功分析 s 或失败时未定义的值的结果。
返回
如果已成功分析 s,则 true;否则,false。
适用于
TryParse(ReadOnlySpan<Char>, Int32)
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
将区域性特定格式的数字的跨度表示形式转换为其等效的 32 位带符号整数。 返回值指示转换是否成功。
public:
 static bool TryParse(ReadOnlySpan<char> s, [Runtime::InteropServices::Out] int % result);public static bool TryParse(ReadOnlySpan<char> s, out int result);static member TryParse : ReadOnlySpan<char> * int -> boolPublic Shared Function TryParse (s As ReadOnlySpan(Of Char), ByRef result As Integer) As Boolean参数
- s
- ReadOnlySpan<Char>
一个范围,包含表示要转换的数字的字符。
- result
- Int32
此方法返回时,如果转换成功,则包含与 s中包含的数字等效的 32 位有符号整数值;如果转换失败,则包含零。 如果 s 参数 null 或 Empty 或表示小于 Int32.MinValue 或大于 Int32.MaxValue,则转换失败。 此参数未初始化传递;将覆盖最初在 result 中提供的任何值。
返回
如果已成功转换 s,则 true;否则,false。
适用于
TryParse(String, Int32)
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
将数字的字符串表示形式转换为其等效的 32 位有符号整数。 返回值指示转换是否成功。
public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] int % result);public static bool TryParse(string s, out int result);public static bool TryParse(string? s, out int result);static member TryParse : string * int -> boolPublic Shared Function TryParse (s As String, ByRef result As Integer) As Boolean参数
- s
- String
包含要转换的数字的字符串。
- result
- Int32
此方法返回时,如果转换成功,则包含与 s中包含的数字等效的 32 位有符号整数值;如果转换失败,则包含零。 如果 s 参数 null 或 Empty,则转换失败,或者表示 小于 int32.MinValue 或大于 Int32.MaxValue的数字。 此参数未初始化传递;将覆盖最初在 result 中提供的任何值。
返回
如果已成功转换 s,则 true;否则,false。
示例
以下示例使用多个不同的字符串值调用 Int32.TryParse(String, Int32) 方法。
using namespace System;
   void TryToParse(String^ value)
   {
      Int32 number;
      bool result = Int32::TryParse(value, number);
      if (result) {
         Console::WriteLine("Converted '{0}' to {1}.", value, number);
      }
      else {
         if (value == nullptr) value = "";
         Console::WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }
void main()
{
      TryToParse(nullptr);
      TryToParse("160519");
      TryToParse("9432.0");
      TryToParse("16,667");
      TryToParse("   -322   ");
      TryToParse("+4302");
      TryToParse("(100);");
      TryToParse("01FA");
}
// The example displays the following output:
//      Attempted conversion of '' failed.
//      Converted '160519' to 160519.
//      Attempted conversion of '9432.0' failed.
//      Attempted conversion of '16,667' failed.
//      Converted '   -322   ' to -322.
//      Converted '+4302' to 4302.
//      Attempted conversion of '(100);' failed.
//      Attempted conversion of '01FA' failed.
using System;
public class Example
{
   public static void Main()
   {
      string[] values = { null, "160519", "9432.0", "16,667",
                          "   -322   ", "+4302", "(100);", "01FA" };
      foreach (var value in values)
      {
         int number;
         bool success = int.TryParse(value, out number);
         if (success)
         {
            Console.WriteLine($"Converted '{value}' to {number}.");
         }
         else
         {
            Console.WriteLine($"Attempted conversion of '{value ?? "<null>"}' failed.");
         }
      }
   }
}
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
open System
let values = 
   [ null; "160519"; "9432.0"; "16,667"
     "   -322   "; "+4302"; "(100);"; "01FA" ]
for value in values do
    match Int32.TryParse value with
    | true, number -> 
        printfn $"Converted '{value}' to {number}."
    | _ -> 
        printfn $"""Attempted conversion of '{if isNull value then "<null>" else value}' failed."""
         
// The example displays the following output:
//       Attempted conversion of '<null>' failed.
//       Converted '160519' to 160519.
//       Attempted conversion of '9432.0' failed.
//       Attempted conversion of '16,667' failed.
//       Converted '   -322   ' to -322.
//       Converted '+4302' to 4302.
//       Attempted conversion of '(100);' failed.
//       Attempted conversion of '01FA' failed.
Module Example
   Public Sub Main()
      Dim values() As String = { Nothing, "160519", "9432.0", "16,667",
                                 "   -322   ", "+4302", "(100);", 
                                 "01FA" }
      For Each value In values
         Dim number As Integer
    
         Dim success As Boolean = Int32.TryParse(value, number)
         If success Then
            Console.WriteLine("Converted '{0}' to {1}.", value, number)
         Else
            Console.WriteLine("Attempted conversion of '{0}' failed.", 
                              If(value ,"<null>"))
         End If     
      Next
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversion of '<null>' failed.
'       Converted '160519' to 160519.
'       Attempted conversion of '9432.0' failed.
'       Attempted conversion of '16,667' failed.
'       Converted '   -322   ' to -322.
'       Converted '+4302' to 4302.
'       Attempted conversion of '(100)' failed.
'       Attempted conversion of '01FA' failed.
TryParse(String, Int32) 方法无法转换的一些字符串如下:
- "9432.0". 转换失败,因为字符串不能包含小数分隔符;它必须仅包含整型数字。 
- "16,667". 转换失败,因为字符串不能包含组分隔符;它必须仅包含整型数字。 
- "(100)". 转换失败,因为字符串不能包含由当前区域性的 NumberFormatInfo.NegativeSign 和 NumberFormatInfo.NumberNegativePattern 属性定义的负号。 
- “01FA”。 转换失败,因为字符串不能包含十六进制数字;它必须仅包含十进制数字。 
注解
              TryParse 方法类似于 Parse 方法,但 TryParse 方法在转换失败时不会引发异常。 它消除了在 s 无效且无法成功分析的情况下使用异常处理来测试 FormatException 的需要。
              s 参数包含多种形式:
[ws][sign]digits[ws]
方括号 ([ 和 ]) 中的项是可选的。 下表描述了每个元素。
| 元素 | 描述 | 
|---|---|
| ws | 可选空格。 | 
| 签名 | 可选符号。 | 
| 位 | 一系列数字,范围从 0 到 9。 | 
              s 参数使用 NumberStyles.Integer 样式进行解释。 除了十进制数字,只允许前导和尾随空格以及前导符号。 若要显式定义样式元素以及 s中存在的特定于区域性的格式信息,请使用 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 方法。
使用为当前系统区域性初始化的 NumberFormatInfo 对象中的格式信息分析 s 参数。 有关详细信息,请参阅 CurrentInfo。
              TryParse 方法的此重载将 s 参数中的所有数字解释为十进制数字。 若要分析十六进制数的字符串表示形式,请调用 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 重载。
另请参阅
- Parse(String)
- ToString()
- 分析 .NET 中的数值字符串
- 示例:.NET Core WinForms 格式设置实用工具 (C#)
- 示例:.NET Core WinForms 格式设置实用工具 (Visual Basic)
适用于
TryParse(ReadOnlySpan<Byte>, IFormatProvider, Int32)
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
尝试将 UTF-8 字符的范围分析为值。
public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = IUtf8SpanParsable<int>::TryParse;public static bool TryParse(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out int result);static member TryParse : ReadOnlySpan<byte> * IFormatProvider * int -> boolPublic Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider, ByRef result As Integer) As Boolean参数
- utf8Text
- ReadOnlySpan<Byte>
要分析的 UTF-8 字符的范围。
- provider
- IFormatProvider
一个对象,提供有关 utf8Text的区域性特定格式设置信息。
- result
- Int32
返回时,包含成功分析 utf8Text 或失败时未定义值的结果。
返回
如果已成功分析 utf8Text,则 true;否则,false。
适用于
TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
尝试将字符范围分析为值。
public:
 static bool TryParse(ReadOnlySpan<char> s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = ISpanParsable<int>::TryParse;public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, out int result);static member TryParse : ReadOnlySpan<char> * IFormatProvider * int -> boolPublic Shared Function TryParse (s As ReadOnlySpan(Of Char), provider As IFormatProvider, ByRef result As Integer) As Boolean参数
- s
- ReadOnlySpan<Char>
要分析的字符范围。
- provider
- IFormatProvider
一个对象,提供有关 s的区域性特定格式设置信息。
- result
- Int32
此方法返回时,包含成功分析 s的结果或失败时未定义的值。
返回
如果已成功分析 s,则 true;否则,false。
适用于
TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Int32)
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
尝试将 UTF-8 字符的范围分析为值。
public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;public static bool TryParse(ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);static member TryParse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider * int -> boolPublic Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean参数
- utf8Text
- ReadOnlySpan<Byte>
要分析的 UTF-8 字符的范围。
- style
- NumberStyles
              utf8Text中可以存在的数字样式的按位组合。
- provider
- IFormatProvider
一个对象,提供有关 utf8Text的区域性特定格式设置信息。
- result
- Int32
返回时,包含成功分析 utf8Text 或失败时未定义值的结果。
返回
如果已成功分析 utf8Text,则 true;否则,false。
适用于
TryParse(ReadOnlySpan<Byte>, Int32)
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
尝试将包含数字字符串表示形式的 UTF-8 字符范围转换为其等效的 32 位带符号整数。
public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, [Runtime::InteropServices::Out] int % result);public static bool TryParse(ReadOnlySpan<byte> utf8Text, out int result);static member TryParse : ReadOnlySpan<byte> * int -> boolPublic Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), ByRef result As Integer) As Boolean参数
- utf8Text
- ReadOnlySpan<Byte>
一个范围,包含表示要转换的数字的 UTF-8 字符。
- result
- Int32
此方法返回时,包含与转换成功时 utf8Text 中包含的数字等效的 32 位有符号整数值;如果转换失败,则包含零。 此参数未初始化传递;将覆盖最初在结果中提供的任何值。
返回
如果已成功转换 utf8Text,则 true;否则,false。
适用于
TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
将指定样式和区域性特定格式的数字的跨度表示形式转换为其等效的 32 位有符号整数。 返回值指示转换是否成功。
public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;public:
 static bool TryParse(ReadOnlySpan<char> s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);public static bool TryParse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);public static bool TryParse(ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * int -> boolPublic Shared Function TryParse (s As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean参数
- s
- ReadOnlySpan<Char>
一个范围,包含表示要转换的数字的字符。 使用 style指定的样式解释范围。
- style
- NumberStyles
枚举值的按位组合,指示 s中可以存在的样式元素。 要指定的典型值为 Integer。
- provider
- IFormatProvider
一个对象,提供有关 s的区域性特定格式设置信息。
- result
- Int32
此方法返回时,如果转换成功,则包含与 s中包含的数字等效的 32 位有符号整数值;如果转换失败,则包含零。 如果 s 参数 null 或 Empty、格式不符合 style,或者表示小于 Int32.MinValue 或大于 Int32.MaxValue,则转换失败。 此参数未初始化传递;将覆盖最初在 result 中提供的任何值。
返回
如果已成功转换 s,则 true;否则,false。
适用于
TryParse(String, NumberStyles, IFormatProvider, Int32)
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
- Source:
- Int32.cs
将指定样式和区域性特定格式的数字的字符串表示形式转换为其等效的 32 位带符号整数。 返回值指示转换是否成功。
public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result);public:
 static bool TryParse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] int % result) = System::Numerics::INumberBase<int>::TryParse;public static bool TryParse(string s, System.Globalization.NumberStyles style, IFormatProvider provider, out int result);public static bool TryParse(string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int result);static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * int -> boolPublic Shared Function TryParse (s As String, style As NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean参数
- s
- String
包含要转换的数字的字符串。 该字符串使用 style指定的样式进行解释。
- style
- NumberStyles
枚举值的按位组合,指示 s中可以存在的样式元素。 要指定的典型值为 Integer。
- provider
- IFormatProvider
一个对象,提供有关 s的区域性特定格式设置信息。
- result
- Int32
此方法返回时,如果转换成功,则包含与 s中包含的数字等效的 32 位有符号整数值;如果转换失败,则包含零。 如果 s 参数 null 或 Empty、格式不符合 style,或者表示小于 Int32.MinValue 或大于 Int32.MaxValue,则转换失败。 此参数未初始化传递;将覆盖最初在 result 中提供的任何值。
返回
如果已成功转换 s,则 true;否则,false。
例外
示例
以下示例使用多个不同的字符串和 NumberStyles 值调用 Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) 方法。
using namespace System;
using namespace System::Globalization;
void CallTryParse(String^ stringToConvert, NumberStyles styles)
{
      Int32 number;
      CultureInfo^ provider;
      // If currency symbol is allowed, use en-US culture. 
      if (((Int32) (styles & NumberStyles::AllowCurrencySymbol)) > 0)
         provider = gcnew CultureInfo("en-US");
      else
         provider = CultureInfo::InvariantCulture;
      bool result = Int32::TryParse(stringToConvert, styles, 
                                   provider, number);
      if (result)
         Console::WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
      else
         Console::WriteLine("Attempted conversion of '{0}' failed.", 
                           Convert::ToString(stringToConvert));
}
void main()
{
      String^ numericString;
      NumberStyles styles;
      numericString = "106779";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);
      numericString = "-30677";
      styles = NumberStyles::None;
      CallTryParse(numericString, styles);
      styles = NumberStyles::AllowLeadingSign;
      CallTryParse(numericString, styles);
      numericString = "301677-";
      CallTryParse(numericString, styles);
      styles = styles | NumberStyles::AllowTrailingSign;
      CallTryParse(numericString, styles);
      numericString = "$10634";
      styles = NumberStyles::Integer;
      CallTryParse(numericString, styles);
      styles = NumberStyles::Integer | NumberStyles::AllowCurrencySymbol;
      CallTryParse(numericString, styles);
      numericString = "10345.00";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);
      numericString = "10345.72";
      styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
      CallTryParse(numericString, styles);
      numericString = "22,593"; 
      styles = NumberStyles::Integer | NumberStyles::AllowThousands;
      CallTryParse(numericString, styles);
      numericString = "12E-01";
      styles = NumberStyles::Integer | NumberStyles::AllowExponent;
      CallTryParse(numericString, styles); 
      numericString = "12E03";
      CallTryParse(numericString, styles); 
      numericString = "80c1";
      CallTryParse(numericString, NumberStyles::HexNumber);
      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles::HexNumber);      
      Console::ReadLine();
}
// The example displays the following output:
//      Converted '106779' to 106779.
//      Attempted conversion of '-30677' failed.
//      Converted '-30677' to -30677.
//      Attempted conversion of '301677-' failed.
//      Converted '301677-' to -301677.
//      Attempted conversion of '$10634' failed.
//      Converted '$10634' to 10634.
//      Converted '10345.00' to 10345.
//      Attempted conversion of '10345.72' failed.
//      Converted '22,593' to 22593.
//      Attempted conversion of '12E-01' failed.
//      Converted '12E03' to 12000.
//      Converted '80c1' to 32961.
//      Attempted conversion of '0x80C1' failed.
using System;
using System.Globalization;
public class StringParsing
{
   public static void Main()
   {
      string numericString;
      NumberStyles styles;
      numericString = "106779";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);
      numericString = "-30677";
      styles = NumberStyles.None;
      CallTryParse(numericString, styles);
      styles = NumberStyles.AllowLeadingSign;
      CallTryParse(numericString, styles);
      numericString = "301677-";
      CallTryParse(numericString, styles);
      styles = styles | NumberStyles.AllowTrailingSign;
      CallTryParse(numericString, styles);
      numericString = "$10634";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);
      styles = NumberStyles.Integer | NumberStyles.AllowCurrencySymbol;
      CallTryParse(numericString, styles);
      numericString = "10345.00";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);
      numericString = "10345.72";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(numericString, styles);
      numericString = "22,593";
      styles = NumberStyles.Integer | NumberStyles.AllowThousands;
      CallTryParse(numericString, styles);
      numericString = "12E-01";
      styles = NumberStyles.Integer | NumberStyles.AllowExponent;
      CallTryParse(numericString, styles);
      numericString = "12E03";
      CallTryParse(numericString, styles);
      numericString = "80c1";
      CallTryParse(numericString, NumberStyles.HexNumber);
      numericString = "0x80C1";
      CallTryParse(numericString, NumberStyles.HexNumber);
   }
   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {
      CultureInfo provider;
      // If currency symbol is allowed, use en-US culture.
      if ((styles & NumberStyles.AllowCurrencySymbol) > 0)
         provider = new CultureInfo("en-US");
      else
         provider = CultureInfo.InvariantCulture;
      bool success = int.TryParse(stringToConvert, styles,
                                   provider, out int number);
      if (success)
         Console.WriteLine($"Converted '{stringToConvert}' to {number}.");
      else
         Console.WriteLine($"Attempted conversion of '{stringToConvert}' failed.");
   }
}
// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
open System
open System.Globalization
let callTryParse (stringToConvert: string) styles =
    let provider =
        // If currency symbol is allowed, use en-US culture.
        if int (styles &&& NumberStyles.AllowCurrencySymbol) > 0 then
            CultureInfo "en-US"
        else
            CultureInfo.InvariantCulture
    match Int32.TryParse(stringToConvert, styles, provider) with
    | true, number ->
        printfn $"Converted '{stringToConvert}' to {number}."
    | _ ->
        printfn $"Attempted conversion of '{stringToConvert}' failed."
[<EntryPoint>]
let main _ =
    let numericString = "106779"
    let styles = NumberStyles.Integer
    callTryParse numericString styles
    let numericString = "-30677"
    let styles = NumberStyles.None
    callTryParse numericString styles
    let styles = NumberStyles.AllowLeadingSign
    callTryParse numericString styles
    let numericString = "301677-"
    callTryParse numericString styles
    let styles = styles ||| NumberStyles.AllowTrailingSign
    callTryParse numericString styles
    let numericString = "$10634"
    let styles = NumberStyles.Integer
    callTryParse numericString styles
    let styles = NumberStyles.Integer ||| NumberStyles.AllowCurrencySymbol
    callTryParse numericString styles
    let numericString = "10345.00"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles
    let numericString = "10345.72"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse numericString styles
    let numericString = "22,593"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowThousands
    callTryParse numericString styles
    let numericString = "12E-01"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowExponent
    callTryParse numericString styles
    let numericString = "12E03"
    callTryParse numericString styles
    let numericString = "80c1"
    callTryParse numericString NumberStyles.HexNumber
    let numericString = "0x80C1"
    callTryParse numericString NumberStyles.HexNumber
    0
// The example displays the following output to the console:
//       Converted '106779' to 106779.
//       Attempted conversion of '-30677' failed.
//       Converted '-30677' to -30677.
//       Attempted conversion of '301677-' failed.
//       Converted '301677-' to -301677.
//       Attempted conversion of '$10634' failed.
//       Converted '$10634' to 10634.
//       Converted '10345.00' to 10345.
//       Attempted conversion of '10345.72' failed.
//       Converted '22,593' to 22593.
//       Attempted conversion of '12E-01' failed.
//       Converted '12E03' to 12000.
//       Converted '80c1' to 32961.
//       Attempted conversion of '0x80C1' failed.
Imports System.Globalization
Module StringParsing
   Public Sub Main()
      Dim numericString As String
      Dim styles As NumberStyles
      
      numericString = "106779"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      numericString = "-30677"
      styles = NumberStyles.None
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.AllowLeadingSign
      CallTryParse(numericString, styles)
      
      numericString = "301677-"
      CallTryParse(numericString, styles)
      
      styles = styles Or NumberStyles.AllowTrailingSign
      CallTryParse(numericString, styles)
      
      numericString = "$10634"
      styles = NumberStyles.Integer
      CallTryParse(numericString, styles)
      
      styles = NumberStyles.Integer Or NumberStyles.AllowCurrencySymbol
      CallTryParse(numericString, styles)
      numericString = "10345.00"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)
      
      numericString = "10345.72"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(numericString, styles)
      numericString = "22,593" 
      styles = NumberStyles.Integer Or NumberStyles.AllowThousands
      CallTryParse(numericString, styles)
      
      numericString = "12E-01"
      styles = NumberStyles.Integer Or NumberStyles.AllowExponent
      CallTryParse(numericString, styles) 
          
      numericString = "12E03"
      CallTryParse(numericString, styles) 
      
      numericString = "80c1"
      CallTryParse(numericString, NumberStyles.HexNumber)
      
      numericString = "0x80C1"
      CallTryParse(numericString, NumberStyles.HexNumber)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String, styles AS NumberStyles)
      Dim number As Integer
      Dim provider As CultureInfo
      
      ' If currency symbol is allowed, use en-US culture.
      If CBool(styles And NumberStyles.AllowCurrencySymbol) Then
         provider = CultureInfo.CurrentCulture
      Else
         provider = New CultureInfo("en-US")
      End If
      
      Dim result As Boolean = Int32.TryParse(stringToConvert, styles, _
                                             provider, number)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number)
      Else
         Console.WriteLine("Attempted conversion of '{0}' failed.", _
                           Convert.ToString(stringToConvert))
      End If                                                                           
   End Sub
End Module
' The example displays the following output to the console:
'       Converted '106779' to 106779.
'       Attempted conversion of '-30677' failed.
'       Converted '-30677' to -30677.
'       Attempted conversion of '301677-' failed.
'       Converted '301677-' to -301677.
'       Attempted conversion of '$10634' failed.
'       Converted '$10634' to 10634.
'       Converted '10345.00' to 10345.
'       Attempted conversion of '10345.72' failed.
'       Converted '22,593' to 22593.
'       Attempted conversion of '12E-01' failed.
'       Converted '12E03' to 12000.
'       Converted '80c1' to 32961.
'       Attempted conversion of '0x80C1' failed.
注解
              TryParse 方法类似于 Parse 方法,但 TryParse 方法在转换失败时不会引发异常。 它消除了在 s 无效且无法成功分析的情况下使用异常处理来测试 FormatException 的需要。
              style 参数定义允许 s 参数中允许的样式元素(如空格或正号或负号),以便分析操作成功。 它必须是 NumberStyles 枚举中的位标志的组合。 根据 style的值,s 参数可能包括以下元素:
[ws][$][sign][digits,]digits[.fractional_digits][e[sign]digits][ws]
或者,如果 style 参数包括 AllowHexSpecifier:
[ws]hexdigits[ws]
方括号 ([ 和 ]) 中的项是可选的。 下表描述了每个元素。
| 元素 | 描述 | 
|---|---|
| ws | 可选空格。 如果 style包含 NumberStyles.AllowLeadingWhite 标志,或者s末尾style包含 NumberStyles.AllowTrailingWhite 标志,则空格可能会显示在s的开头。 | 
| $ | 区域性特定的货币符号。 字符串中的位置由 provider参数的 GetFormat 方法返回的 NumberFormatInfo 对象的 CurrencyPositivePattern 属性定义。 如果style包含 NumberStyles.AllowCurrencySymbol 标志,货币符号可以出现在s中。 | 
| 签名 | 可选符号。 如果 style包含 NumberStyles.AllowLeadingSign 或 NumberStyles.AllowTrailingSign 标志,符号符号可以出现在s中。 | 
| 位 | 从 0 到 9 的数字序列。 | 
| 、 | 区域性特定的千位分隔符。 如果 style包含 NumberStyles.AllowThousands 标志,则由provider指定的区域性的千位分隔符可以出现在s中。 | 
| 。 | 区域性特定的小数点符号。 如果 style包含 NumberStyles.AllowDecimalPoint 标志,则由provider指定的区域性的小数点符号可以出现在s中。 | 
| fractional_digits | 数字 0 的一个或多个匹配项。 仅当 style包含 NumberStyles.AllowDecimalPoint 标志时,小数位数才会显示在s中。 | 
| e | “e”或“E”字符,指示该值以指数表示法表示。 如果 style包含 NumberStyles.AllowExponent 标志,s参数可以表示指数表示法中的数字。 | 
| hexdigits | 从 0 到 f 或 0 到 F 的十六进制数字序列。 | 
注意
无论 style 参数的值如何,分析操作都会忽略 s 中任何终止的 NUL (U+0000) 字符。
仅包含十进制数字(对应于 NumberStyles.None 标志)的字符串始终成功分析。 其余大部分 NumberStyles 成员控制可能但不需要存在于此输入字符串中的元素。 下表指示单个 NumberStyles 成员如何影响 s中可能存在的元素。
| 非复合 NumberStyles 值 | 除数字外允许的元素 | 
|---|---|
| NumberStyles.None | 仅十进制数字。 | 
| NumberStyles.AllowDecimalPoint | 小数点(.)和 fractional_digits 元素。 但是,fractional_digits 必须仅包含一个或多个数字,否则该方法返回 false。 | 
| NumberStyles.AllowExponent | s参数也可以使用指数表示法。 如果s表示指数表示法中的数字,则它必须表示 Int32 数据类型范围内没有非零小数分量的整数。 | 
| NumberStyles.AllowLeadingWhite | s开头的 ws 元素。 | 
| NumberStyles.AllowTrailingWhite | s末尾的 ws 元素。 | 
| NumberStyles.AllowLeadingSign | 符号可以出现在 位之前。 | 
| NumberStyles.AllowTrailingSign | 数字后,可以显示一个符号。 | 
| NumberStyles.AllowParentheses | 符号 元素,以括住数值的括号形式。 | 
| NumberStyles.AllowThousands | 千位分隔符(,)元素。 | 
| NumberStyles.AllowCurrencySymbol | $ 元素。 | 
| NumberStyles.Currency | 所有元素。 s参数不能表示十六进制数或指数表示法中的数字。 | 
| NumberStyles.Float | ws 元素位于 s的开头或末尾,符号s开头,以及小数点(.)符号。s参数也可以使用指数表示法。 | 
| NumberStyles.Number | ws、符号、千位分隔符(、)和小数点(.)元素。 | 
| NumberStyles.Any | 除 s之外的所有样式都不能表示十六进制数。 | 
如果使用 NumberStyles.AllowHexSpecifier 标志,s 必须是没有前缀的十六进制值。 例如,“C9AF3”已成功分析,但“0xC9AF3”不会。 
              style 中唯一可以存在的其他标志是 NumberStyles.AllowLeadingWhite 和 NumberStyles.AllowTrailingWhite。 (NumberStyles 枚举具有包含两个空格标志的复合样式 NumberStyles.HexNumber。
              provider 参数是 IFormatProvider 实现,如 CultureInfo 对象或 NumberFormatInfo 对象,其 GetFormat 方法返回 NumberFormatInfo 对象。 
              NumberFormatInfo 对象提供有关 s格式的区域性特定信息。 如果 providernull,则使用当前区域性的 NumberFormatInfo 对象。
另请参阅
- Parse(String)
- NumberStyles
- ToString()
- 分析 .NET 中的数值字符串