BigInteger.TryParse 方法

定義

嘗試將數字的字串表示轉換成其相等的 BigInteger,並傳回一個值表示轉換是否成功。Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

多載

TryParse(ReadOnlySpan<Char>, BigInteger)

嘗試將所指定唯讀字元範圍中包含的數字表示法轉換為其 BigInteger 對等項目,並傳回指出轉換是否成功的值。Tries to convert the representation of a number contained in the specified read-only character span, to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

TryParse(String, BigInteger)

嘗試將數字的字串表示轉換成其相等的 BigInteger,並傳回一個值表示轉換是否成功。Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, BigInteger)

嘗試將數字的字串表示轉換成其相等的 BigInteger,並傳回一個值表示轉換是否成功。Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

TryParse(String, NumberStyles, IFormatProvider, BigInteger)

使用指定的文化特性特定格式資訊和格式樣式,將日期和時間的指定字串表示轉換為其對等的 BigInteger,並傳回值,這個值表示轉換是否成功。Tries to convert the string representation of a number in a specified style and culture-specific format to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

TryParse(ReadOnlySpan<Char>, BigInteger)

嘗試將所指定唯讀字元範圍中包含的數字表示法轉換為其 BigInteger 對等項目,並傳回指出轉換是否成功的值。Tries to convert the representation of a number contained in the specified read-only character span, to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(ReadOnlySpan<char> value, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public static bool TryParse (ReadOnlySpan<char> value, out System.Numerics.BigInteger result);
static member TryParse : ReadOnlySpan<char> * BigInteger -> bool
Public Shared Function TryParse (value As ReadOnlySpan(Of Char), ByRef result As BigInteger) As Boolean

參數

value
ReadOnlySpan<Char>

以唯讀字元範圍形式表示的數字表示法。The representation of a number as a read-only span of characters.

result
BigInteger

當這個方法傳回時,如果轉換成功,則會包含相當於 value 中所含之數字的 BigInteger;如果轉換失敗則為零 (0)。When this method returns, contains the BigInteger equivalent to the number that is contained in value, or zero (0) if the conversion fails. value 參數是空字元範圍或不是正確的格式,則轉換會失敗。The conversion fails if the value parameter is an empty character span or is not of the correct format. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

如果 value 轉換成功,則為 true,否則為 falsetrue if value was converted successfully; otherwise, false.

另請參閱

TryParse(String, BigInteger)

嘗試將數字的字串表示轉換成其相等的 BigInteger,並傳回一個值表示轉換是否成功。Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(System::String ^ value, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public static bool TryParse (string value, out System.Numerics.BigInteger result);
static member TryParse : string * BigInteger -> bool
Public Shared Function TryParse (value As String, ByRef result As BigInteger) As Boolean

參數

value
String

數字的字串表示。The string representation of a number.

result
BigInteger

當這個方法傳回時,如果轉換成功,則會包含相當於 value 中所含之數字的 BigInteger;如果轉換失敗則為零 (0)。When this method returns, contains the BigInteger equivalent to the number that is contained in value, or zero (0) if the conversion fails. 轉換失敗的狀況包括:如果 value 參數為 null 或不是正確的格式。The conversion fails if the value parameter is null or is not of the correct format. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

如果 value 轉換成功,則為 true,否則為 falsetrue if value was converted successfully; otherwise, false.

例外狀況

valuenullvalue is null.

範例

下列範例會使用 TryParse(String, BigInteger) 方法來具現化兩個 BigInteger 物件。The following example uses the TryParse(String, BigInteger) method to instantiate two BigInteger objects. 如果轉換成功,它會將每個物件乘以另一個數位,然後呼叫 Compare 方法,以判斷兩個物件之間的關聯性。If the conversions succeed, it multiplies each object by another number and then calls the Compare method to determine the relationship between the two objects.

BigInteger number1, number2;
bool succeeded1 = BigInteger.TryParse("-12347534159895123", out number1);
bool succeeded2 = BigInteger.TryParse("987654321357159852", out number2);
if (succeeded1 && succeeded2)
{
   number1 *= 3;
   number2 *= 2;
   switch (BigInteger.Compare(number1, number2))
   {
      case -1:
         Console.WriteLine("{0} is greater than {1}.", number2, number1);
         break;
      case 0:
         Console.WriteLine("{0} is equal to {1}.", number1, number2);
         break;
      case 1:
         Console.WriteLine("{0} is greater than {1}.", number1, number2);
         break;
   }      
}
else
{
   if (! succeeded1) 
      Console.WriteLine("Unable to initialize the first BigInteger value.");

   if (! succeeded2)
      Console.WriteLine("Unable to initialize the second BigInteger value.");
}
// The example displays the following output:
//      1975308642714319704 is greater than -37042602479685369.
Dim number1 As BigInteger = BigInteger.Zero
Dim number2 As BigInteger = BigInteger.Zero
Dim succeeded1 As Boolean = BigInteger.TryParse("-12347534159895123", number1)
Dim succeeded2 As Boolean = BigInteger.TryParse("987654321357159852", number2)
If succeeded1 AndAlso succeeded2
   number1 *= 3
   number2 *= 2
   Select Case BigInteger.Compare(number1, number2)
      Case -1
         Console.WriteLine("{0} is greater than {1}.", number2, number1)
      Case 0
         Console.WriteLine("{0} is equal to {1}.", number1, number2)
      Case 1
         Console.WriteLine("{0} is greater than {1}.", number1, number2)
   End Select      
Else
   If Not succeeded1 Then 
      Console.WriteLine("Unable to initialize the first BigInteger value.")
   End If
   If Not succeeded2 Then
      Console.WriteLine("Unable to initialize the second BigInteger value.")
   
   End If
End If
' The example displays the following output:
'      1975308642714319704 is greater than -37042602479685369.

備註

TryParse(String, BigInteger) 方法就像 Parse(String) 方法,不同的是,它不會在轉換失敗時擲回例外狀況。The TryParse(String, BigInteger) method is like the Parse(String) method, except that it does not throw an exception if the conversion fails. 如果 value 無效,而且無法成功剖析,這個方法就不需要使用例外狀況處理來測試 FormatExceptionThis method eliminates the need to use exception handling to test for a FormatException if value is invalid and cannot be successfully parsed.

value 參數應該是十進位數的字串表示,其格式如下:The value parameter should be the string representation of a decimal number in the following form:

[ws][sign]數位[ws][ws][sign]digits[ws]

在方括號 ([ 和 ]) 中的項目是選擇性的項目。Elements in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 描述Description
wsws 選擇性的空白字元。Optional white space.
簽署sign 選擇性的正負號。An optional sign. 有效的正負號字元是由目前文化特性的 NumberFormatInfo.NegativeSignNumberFormatInfo.PositiveSign 屬性所決定。Valid sign characters are determined by the NumberFormatInfo.NegativeSign and NumberFormatInfo.PositiveSign properties of the current culture.
digitsdigits 十進位數的序列,範圍介於0到9之間。A sequence of decimal digits ranging from 0 to 9.

注意

value 參數所指定的字串不能包含任何群組分隔符號或小數分隔符號,而且不能有小數部分。The string specified by the value parameter cannot contain any group separators or decimal separator, and it cannot have a decimal portion.

value 參數會使用 NumberStyles.Integer 樣式來加以解讀。The value parameter is interpreted by using the NumberStyles.Integer style. 除了十進位數以外,只允許開頭和尾端空格加上前置正負號。In addition to the decimal digits, only leading and trailing spaces with a leading sign are allowed. 若要使用 value中可顯示的特定文化特性格式資訊,明確地定義樣式元素,請呼叫 TryParse(String, NumberStyles, IFormatProvider, BigInteger) 方法。To explicitly define the style elements with the culture-specific formatting information that can be present in value, call the TryParse(String, NumberStyles, IFormatProvider, BigInteger) method.

value 參數是使用目前文化特性的 NumberFormatInfo 物件中的格式資訊進行剖析。The value parameter is parsed by using the formatting information in a NumberFormatInfo object for the current culture. 如需詳細資訊,請參閱NumberFormatInfo.CurrentInfoFor more information, see NumberFormatInfo.CurrentInfo.

這個多載會將 value 參數中的所有數位都視為十進位數。This overload interprets all digits in the value parameter as decimal digits. 若要剖析十六進位數位的字串表示,請改為呼叫 TryParse(String, NumberStyles, IFormatProvider, BigInteger) 多載。To parse the string representation of a hexadecimal number, call the TryParse(String, NumberStyles, IFormatProvider, BigInteger) overload instead.

另請參閱

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, BigInteger)

嘗試將數字的字串表示轉換成其相等的 BigInteger,並傳回一個值表示轉換是否成功。Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(ReadOnlySpan<char> value, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public static bool TryParse (ReadOnlySpan<char> value, System.Globalization.NumberStyles style, IFormatProvider provider, out System.Numerics.BigInteger result);
static member TryParse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider * BigInteger -> bool
Public Shared Function TryParse (value As ReadOnlySpan(Of Char), style As NumberStyles, provider As IFormatProvider, ByRef result As BigInteger) As Boolean

參數

value
ReadOnlySpan<Char>

以唯讀字元範圍形式表示的數字表示法。The representation of a number as a read-only span of characters.

style
NumberStyles

列舉值的位元組合,其表示 value 中可以存在的樣式項目。A bitwise combination of enumeration values that indicates the style elements that can be present in value. 一般會指定的值是 IntegerA typical value to specify is Integer.

provider
IFormatProvider

物件,其提供關於 value 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about value.

result
BigInteger

當這個方法傳回時,如果轉換成功,則會包含相當於 value 中所含之數字的 BigInteger;如果轉換失敗則為 ZeroWhen this method returns, contains the BigInteger equivalent to the number that is contained in value, or Zero if the conversion failed. value 參數是空字元範圍或不是符合 style 的格式,則轉換會失敗。The conversion fails if the value parameter is an empty character span or is not in a format that is compliant with style. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

如果 value 轉換成功,則為 true,否則為 falsetrue if value was converted successfully; otherwise, false.

例外狀況

style 不是 NumberStyles 值。style is not a NumberStyles value.

-或--or- style 包含 AllowHexSpecifierHexNumber 旗標和其他值。style includes the AllowHexSpecifier or HexNumber flag along with another value.

備註

這個多載就像 Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) 方法,不同的是,如果轉換失敗,則不會擲回例外狀況。This overload is like the Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) method, except that it does not throw an exception if the conversion fails. 如果 value 無效,而且無法成功剖析,這個方法就不需要使用例外狀況處理來測試 FormatExceptionThis method eliminates the need to use exception handling to test for a FormatException if value is invalid and cannot be parsed successfully.

style 參數會定義在 value 參數中允許的樣式元素(例如空白字元或正數或負號),使剖析作業成功。The style parameter defines the style elements (such as white space or a positive or negative sign) that are allowed in the value parameter for the parse operation to succeed. 它必須是來自 NumberStyles 列舉的位旗標組合。It must be a combination of bit flags from the NumberStyles enumeration. 根據 style的值,value 參數可能包含下列元素:Depending on the value of style, the value parameter may include the following elements:

[ws][$][sign][數位,]數位[。fractional_digits] [E [sign]exponential_digits] [ws][ws][$][sign][digits,]digits[.fractional_digits][E[sign]exponential_digits][ws]

如果 style 參數包含 AllowHexSpecifier,則 value 參數可能包含下列元素:If the style parameter includes AllowHexSpecifier, the value parameter may include the following elements:

[ws]hexdigits[ws][ws]hexdigits[ws]

在方括號 ([ 和 ]) 中的項目是選擇性的項目。Elements in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 描述Description
wsws 選擇性的空白字元。Optional white space. 如果 style 包含 NumberStyles.AllowLeadingWhite 旗標,或如果 style 包含 NumberStyles.AllowTrailingWhite 旗標,就會在 value 的結尾處 value 顯示空白字元。White space can appear at the start of value if style includes the NumberStyles.AllowLeadingWhite flag, or at the end of value if style includes the NumberStyles.AllowTrailingWhite flag.
$ 特定文化特性的貨幣符號。A culture-specific currency symbol. 其在 value 中的位置是由 provider 參數的 GetFormat 方法所傳回 NumberFormatInfo 物件的 CurrencyPositivePattern 屬性所定義。Its position in value is defined by the CurrencyPositivePattern property of the NumberFormatInfo object returned by the GetFormat method of the provider parameter. 如果 style 包含 NumberStyles.AllowCurrencySymbol 旗標,貨幣符號可能會出現在 value 中。The currency symbol can appear in value if style includes the NumberStyles.AllowCurrencySymbol flag.
簽署sign 選擇性的正負號。An optional sign. 如果 style 包含 NumberStyles.AllowLeadingSign 旗標,則正負號可以出現在 value 的開頭,如果 style 包含 NumberStyles.AllowTrailingSign 旗標,它可以出現在 value 的結尾。The sign can appear at the start of value if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of value if style includes the NumberStyles.AllowTrailingSign flag. 如果 style 包含 NumberStyles.AllowParentheses 旗標,則可以在 value 中使用括弧來表示負數值。Parentheses can be used in value to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
digitsdigits 從0到9的數位序列。A sequence of digits from 0 through 9.
, 文化特性特定的群組分隔符號。A culture-specific group separator. 如果 style 包含 NumberStyles.AllowThousands 旗標,provider 所指定的文化特性群組分隔符號會出現在 value 中。The group separator of the culture specified by provider can appear in value if style includes the NumberStyles.AllowThousands flag.
.. 文化特性特定的小數點符號。A culture-specific decimal point symbol. 如果 style 包含 NumberStyles.AllowDecimalPoint 旗標,provider 所指定文化特性的小數點符號會出現在 value 中。The decimal point symbol of the culture specified by provider can appear in value if style includes the NumberStyles.AllowDecimalPoint flag.
fractional_digitsfractional_digits 數位0的一或多個出現次數。One or more occurrences of the digit 0. 只有在 style 包含 NumberStyles.AllowDecimalPoint 旗標時,小數位數才會出現在 value 中。Fractional digits can appear in value only if style includes the NumberStyles.AllowDecimalPoint flag.
EE "E" 或 "E" 字元,表示該值是以指數(科學)標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. 如果 style 包含 NumberStyles.AllowExponent 旗標,value 參數可以表示指數標記法中的數位。The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential_digitsexponential_digits 從0到9的數位序列。A sequence of digits from 0 through 9. 如果 style 包含 NumberStyles.AllowExponent 旗標,value 參數可以表示指數標記法中的數位。The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
hexdigitshexdigits 從0到 f 的十六進位數位序列,或0到 F。A sequence of hexadecimal digits from 0 through f, or 0 through F.

注意

不論 style 引數的值為何,剖析作業都會忽略 s 中的任何終止 NUL (U + 0000)字元。Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

非複合 NumberStylesNon-composite NumberStyles values 除了數位之外,值中允許的元素Elements permitted in value in addition to digits
None 僅限十進位數。Decimal digits only.
AllowDecimalPoint 小數點(.)和fractional_digits元素。The decimal point (.) and fractional_digits elements. 不過, fractional_digits必須只包含一或多個0位數,否則方法會傳回 falseHowever, fractional_digits must consist of only one or more 0 digits, or the method returns false.
AllowExponent "E" 或 "E" 字元,表示指數標記法,以及exponential_digitsThe "e" or "E" character, which indicates exponential notation, along with exponential_digits. 如果 value 代表指數標記法中的數位,則不能有非零的小數部分。If value represents a number in exponential notation, it cannot have a non-zero, fractional component.
AllowLeadingWhite value開頭的ws元素。The ws element at the start of value.
AllowTrailingWhite value結尾的ws元素。The ws element at the end of value.
AllowLeadingSign 數位前面的正負號元素。The sign element before digits.
AllowTrailingSign 數位後面的sign元素。The sign element after digits.
AllowParentheses 以括弧形式括住數值的sign元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 群組分隔符號()元素。The group separator (,) element.
AllowCurrencySymbol Currency ($)元素。The currency ($) element.
Currency 所有元素。All elements. 不過,value 不能以指數標記法來表示十六進位數位或數位。However, value cannot represent a hexadecimal number or a number in exponential notation.
Float value開頭或結尾處的ws元素、value開頭和小數點(.)符號的符號The ws element at the start or end of value, sign at the start of value, and the decimal point (.) symbol. value 參數也可以使用指數標記法。The value parameter can also use exponential notation.
Number Wssign、group 分隔符號()和小數點(.)元素。The ws, sign, group separator (,), and decimal point (.) elements.
Any 所有元素。All elements. 不過,value 不能代表十六進位數位。However, value cannot represent a hexadecimal number.

如果使用 NumberStyles.AllowHexSpecifier 旗標,value 必須是十六進位值。If the NumberStyles.AllowHexSpecifier flag is used, value must be a hexadecimal value. style 中唯一可以出現的其他旗標是 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteThe only other flags that can be present in style are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. NumberStyles 列舉具有同時包含空白字元旗標的複合樣式,HexNumber。)(The NumberStyles enumeration has a composite style, HexNumber, that includes both white-space flags.)

provider 參數是 IFormatProvider 的實作為。The provider parameter is an IFormatProvider implementation. 它的 GetFormat 方法會傳回 NumberFormatInfo 物件,提供 value格式的特定文化特性資訊。Its GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of value. provider 參數可以是下列任何一項:The provider parameter can be any one of the following:

如果 null``provider,則會使用目前文化特性的 NumberFormatInfo 物件。If provider is null, the NumberFormatInfo object for the current culture is used.

另請參閱

TryParse(String, NumberStyles, IFormatProvider, BigInteger)

使用指定的文化特性特定格式資訊和格式樣式,將日期和時間的指定字串表示轉換為其對等的 BigInteger,並傳回值,這個值表示轉換是否成功。Tries to convert the string representation of a number in a specified style and culture-specific format to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.

public:
 static bool TryParse(System::String ^ value, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Numerics::BigInteger % result);
public static bool TryParse (string value, System.Globalization.NumberStyles style, IFormatProvider provider, out System.Numerics.BigInteger result);
static member TryParse : string * System.Globalization.NumberStyles * IFormatProvider * BigInteger -> bool
Public Shared Function TryParse (value As String, style As NumberStyles, provider As IFormatProvider, ByRef result As BigInteger) As Boolean

參數

value
String

數字的字串表示。The string representation of a number. 這個字串使用 style 指定的樣式來解譯。The string is interpreted using the style specified by style.

style
NumberStyles

列舉值的位元組合,表示 value 中可以存在的樣式項目。A bitwise combination of enumeration values that indicates the style elements that can be present in value. 一般會指定的值是 IntegerA typical value to specify is Integer.

provider
IFormatProvider

物件,其提供關於 value 的特定文化特性格式資訊。An object that supplies culture-specific formatting information about value.

result
BigInteger

當這個方法傳回時,如果轉換成功,則會包含相當於 value 中所含之數字的 BigInteger;如果轉換失敗則為 ZeroWhen this method returns, contains the BigInteger equivalent to the number that is contained in value, or Zero if the conversion failed. 轉換失敗的狀況包括:如果 value 參數為 null 或格式不符合 styleThe conversion fails if the value parameter is null or is not in a format that is compliant with style. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

傳回

如果 true 參數轉換成功,則為 value,否則為 falsetrue if the value parameter was converted successfully; otherwise, false.

例外狀況

style 不是 NumberStyles 值。style is not a NumberStyles value.

-或--or- style 包含 AllowHexSpecifierHexNumber 旗標和其他值。style includes the AllowHexSpecifier or HexNumber flag along with another value.

範例

下列範例會使用 styleprovider 參數的各種值組合,對 TryParse(String, NumberStyles, IFormatProvider, BigInteger) 方法進行一些呼叫。The following example makes some calls to the TryParse(String, NumberStyles, IFormatProvider, BigInteger) method using various combinations of values for the style and provider parameters.

string numericString;
BigInteger number = BigInteger.Zero;

// Call TryParse with default values of style and provider.
numericString = "  -300   ";
if (BigInteger.TryParse(numericString, NumberStyles.Integer, 
                       null, out number))
   Console.WriteLine("'{0}' was converted to {1}.", 
                     numericString, number);                    
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.", 
                     numericString);

// Call TryParse with the default value of style and 
// a provider supporting the tilde as negative sign.
numericString = "  -300   ";
if (BigInteger.TryParse(numericString, NumberStyles.Integer,
                       new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);                             
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with only AllowLeadingWhite and AllowTrailingWhite.
// Method returns false because of presence of negative sign.
numericString = "  -500   ";
if (BigInteger.TryParse(numericString,
                        NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
                        new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);                             
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with AllowHexSpecifier and a hex value.
numericString = "F14237FFAAC086455192";
if (BigInteger.TryParse(numericString,
                        NumberStyles.AllowHexSpecifier,
                        null, out number))
   Console.WriteLine("'{0}' was converted to {1} (0x{1:x}).",
                     numericString, number);                             
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with AllowHexSpecifier and a negative hex value.
// Conversion fails because of presence of negative sign.
numericString = "-3af";
if (BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier,
                       new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);       
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with only NumberStyles.None.
// Conversion fails because of presence of white space and sign.
numericString = " -300 ";
if (BigInteger.TryParse(numericString, NumberStyles.None,
                       new BigIntegerFormatProvider(), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);         
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);
                                            
// Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
// Conversion fails because the string is formatted for the en-US culture.
numericString = "9,031,425,666,123,546.00";
if (BigInteger.TryParse(numericString, NumberStyles.Any,
                       new CultureInfo("fr-FR"), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);                     
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);

// Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
// Conversion succeeds because the string is properly formatted 
// For the fr-FR culture.
numericString = "9 031 425 666 123 546,00";
if (BigInteger.TryParse(numericString, NumberStyles.Any,
                       new CultureInfo("fr-FR"), out number))
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number);                 
else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString);
// The example displays the following output:
//    '  -300   ' was converted to -300.
//    Conversion of '  -300   ' to a BigInteger failed.
//    Conversion of '  -500   ' to a BigInteger failed.
//    'F14237FFAAC086455192' was converted to -69613977002644837412462 (0xf14237ffaac086455192).
//    Conversion of '-3af' to a BigInteger failed.
//    Conversion of ' -300 ' to a BigInteger failed.
//    Conversion of '9,031,425,666,123,546.00' to a BigInteger failed.
//    '9 031 425 666 123 546,00' was converted to 9031425666123546.      
Dim numericString As String
Dim number As BigInteger = BigInteger.Zero

' Call TryParse with default values of style and provider.
numericString = "  -300   "
If BigInteger.TryParse(numericString, NumberStyles.Integer,
                       Nothing, number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with the default value of style and 
' a provider supporting the tilde as negative sign.
numericString = "  -300   "
If BigInteger.TryParse(numericString, NumberStyles.Integer,
                       New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with only AllowLeadingWhite and AllowTrailingWhite.
' Method returns false because of presence of negative sign.
numericString = "  -500   "
If BigInteger.TryParse(numericString,
                    NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite,
                    New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with AllowHexSpecifier and a hex value.
numericString = "F14237FFAAC086455192"
If BigInteger.TryParse(numericString,
                    NumberStyles.AllowHexSpecifier,
                    Nothing, number) Then
   Console.WriteLine("'{0}' was converted to {1} (0x{1:x}).",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with AllowHexSpecifier and a negative hex value.
' Conversion fails because of presence of negative sign.
numericString = "-3af"
If BigInteger.TryParse(numericString, NumberStyles.AllowHexSpecifier,
                       New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If                                             

' Call TryParse with only NumberStyles.None.
' Conversion fails because of presence of white space and sign.
numericString = " -300 "
If BigInteger.TryParse(numericString, NumberStyles.None,
                       New BigIntegerFormatProvider(), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If 
                                            
' Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
' Conversion fails because the string is formatted for the en-US culture.
numericString = "9,031,425,666,123,546.00"
If BigInteger.TryParse(numericString, NumberStyles.Any,
                       New CultureInfo("fr-FR"), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If

' Call TryParse with NumberStyles.Any and a provider for the fr-FR culture.
' Conversion succeeds because the string is properly formatted 
' For the fr-FR culture.
numericString = "9 031 425 666 123 546,00"
If BigInteger.TryParse(numericString, NumberStyles.Any,
                       New CultureInfo("fr-FR"), number) Then
   Console.WriteLine("'{0}' was converted to {1}.",
                     numericString, number)                             
Else
   Console.WriteLine("Conversion of '{0}' to a BigInteger failed.",
                     numericString)
End If
' The example displays the following output:
'    '  -300   ' was converted to -300.
'    Conversion of '  -300   ' to a BigInteger failed.
'    Conversion of '  -500   ' to a BigInteger failed.
'    'F14237FFAAC086455192' was converted to -69613977002644837412462 (0xf14237ffaac086455192).
'    Conversion of '-3af' to a BigInteger failed.
'    Conversion of ' -300 ' to a BigInteger failed.
'    Conversion of '9,031,425,666,123,546.00' to a BigInteger failed.
'    '9 031 425 666 123 546,00' was converted to 9031425666123546.      

數個 TryParse(String, NumberStyles, IFormatProvider, BigInteger) 方法的個別呼叫會傳遞下列 BigIntegerFormatProvider 類別的實例,其會將波狀符號(~)定義為負號。A number of the individual calls to the TryParse(String, NumberStyles, IFormatProvider, BigInteger) method pass an instance of the following BigIntegerFormatProvider class, which defines a tilde (~) as the negative sign.

public class BigIntegerFormatProvider : IFormatProvider
{
   public object GetFormat(Type formatType) 
   {
      if (formatType == typeof(NumberFormatInfo)) 
      {
         NumberFormatInfo numberFormat = new NumberFormatInfo();
         numberFormat.NegativeSign = "~";
         return numberFormat;
      }
      else
      {
         return null;
      }      
   }
}
Public Class BigIntegerFormatProvider : Implements IFormatProvider
   Public Function GetFormat(formatType As Type) As Object _
                            Implements IFormatProvider.GetFormat
      If formatType Is GetType(NumberFormatInfo) Then
         Dim numberFormat As New NumberFormatInfo
         numberFormat.NegativeSign = "~"
         Return numberFormat
      Else
         Return Nothing
      End If      
   End Function
End Class

備註

TryParse(String, NumberStyles, IFormatProvider, BigInteger) 方法就像 Parse(String, NumberStyles, IFormatProvider) 方法,不同的是,它不會在轉換失敗時擲回例外狀況。The TryParse(String, NumberStyles, IFormatProvider, BigInteger) method is like the Parse(String, NumberStyles, IFormatProvider) method, except that it does not throw an exception if the conversion fails. 如果 value 無效,而且無法成功剖析,這個方法就不需要使用例外狀況處理來測試 FormatExceptionThis method eliminates the need to use exception handling to test for a FormatException if value is invalid and cannot be parsed successfully.

style 參數會定義在 value 參數中允許的樣式元素(例如空白字元或正數或負號),使剖析作業成功。The style parameter defines the style elements (such as white space or a positive or negative sign) that are allowed in the value parameter for the parse operation to succeed. 它必須是來自 NumberStyles 列舉的位旗標組合。It must be a combination of bit flags from the NumberStyles enumeration. 根據 style的值,value 參數可能包含下列元素:Depending on the value of style, the value parameter may include the following elements:

[ws][$][sign][數位,]數位[。fractional_digits] [E [sign]exponential_digits] [ws][ws][$][sign][digits,]digits[.fractional_digits][E[sign]exponential_digits][ws]

如果 style 參數包含 AllowHexSpecifier,則 value 參數可能包含下列元素:If the style parameter includes AllowHexSpecifier, the value parameter may include the following elements:

[ws]hexdigits[ws][ws]hexdigits[ws]

在方括號 ([ 和 ]) 中的項目是選擇性的項目。Elements in square brackets ([ and ]) are optional. 下表說明每個元素。The following table describes each element.

項目Element 描述Description
wsws 選擇性的空白字元。Optional white space. 如果 style 包含 NumberStyles.AllowLeadingWhite 旗標,或如果 style 包含 NumberStyles.AllowTrailingWhite 旗標,就會在 value 的結尾處 value 顯示空白字元。White space can appear at the start of value if style includes the NumberStyles.AllowLeadingWhite flag, or at the end of value if style includes the NumberStyles.AllowTrailingWhite flag.
$ 特定文化特性的貨幣符號。A culture-specific currency symbol. 其在字串中的位置是由 provider 參數的 GetFormat 方法所傳回之 NumberFormatInfo 物件的 CurrencyPositivePattern 屬性所定義。Its position in the string is defined by the CurrencyPositivePattern property of the NumberFormatInfo object returned by the GetFormat method of the provider parameter. 如果 style 包含 NumberStyles.AllowCurrencySymbol 旗標,貨幣符號可能會出現在 value 中。The currency symbol can appear in value if style includes the NumberStyles.AllowCurrencySymbol flag.
簽署sign 選擇性的正負號。An optional sign. 如果 style 包含 NumberStyles.AllowLeadingSign 旗標,則正負號可以出現在 value 的開頭,如果 style 包含 NumberStyles.AllowTrailingSign 旗標,它可以出現在 value 的結尾。The sign can appear at the start of value if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of value if style includes the NumberStyles.AllowTrailingSign flag. 如果 style 包含 NumberStyles.AllowParentheses 旗標,則可以在 value 中使用括弧來表示負數值。Parentheses can be used in value to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
digitsdigits 從0到9的數位序列。A sequence of digits from 0 through 9.
, 文化特性特定的群組分隔符號。A culture-specific group separator. 如果 style 包含 NumberStyles.AllowThousands 旗標,provider 所指定的文化特性群組分隔符號會出現在 value 中。The group separator of the culture specified by provider can appear in value if style includes the NumberStyles.AllowThousands flag.
.. 文化特性特定的小數點符號。A culture-specific decimal point symbol. 如果 style 包含 NumberStyles.AllowDecimalPoint 旗標,provider 所指定文化特性的小數點符號會出現在 value 中。The decimal point symbol of the culture specified by provider can appear in value if style includes the NumberStyles.AllowDecimalPoint flag.
fractional_digitsfractional_digits 數位0的一或多個出現次數。One or more occurrences of the digit 0. 只有在 style 包含 NumberStyles.AllowDecimalPoint 旗標時,小數位數才會出現在 value 中。Fractional digits can appear in value only if style includes the NumberStyles.AllowDecimalPoint flag.
EE "E" 或 "E" 字元,表示該值是以指數(科學)標記法表示。The "e" or "E" character, which indicates that the value is represented in exponential (scientific) notation. 如果 style 包含 NumberStyles.AllowExponent 旗標,value 參數可以表示指數標記法中的數位。The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential_digitsexponential_digits 從0到9的數位序列。A sequence of digits from 0 through 9. 如果 style 包含 NumberStyles.AllowExponent 旗標,value 參數可以表示指數標記法中的數位。The value parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
hexdigitshexdigits 從0到 f 的十六進位數位序列,或0到 F。A sequence of hexadecimal digits from 0 through f, or 0 through F.

注意

不論 style 引數的值為何,剖析作業都會忽略 s 中的任何終止 NUL (U + 0000)字元。Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

只有十進位數的字串(對應至 NumberStyles.None 旗標)一律會成功剖析。A string with decimal digits only (which corresponds to the NumberStyles.None flag) always parses successfully. 在此輸入字串中,大部分的其餘 NumberStyles 成員控制項可能存在,但不需要存在。Most of the remaining NumberStyles members control elements that may be present, but are not required to be present, in this input string. 下表指出個別 NumberStyles 成員如何影響 value中可能存在的元素。The following table indicates how individual NumberStyles members affect the elements that may be present in value.

非複合 NumberStylesNon-composite NumberStyles values 除了數位之外,值中允許的元素Elements permitted in value in addition to digits
None 僅限十進位數。Decimal digits only.
AllowDecimalPoint 小數點(.)和fractional_digits元素。The decimal point (.) and fractional_digits elements. 不過, fractional_digits必須只包含一或多個0位數,否則方法會傳回 falseHowever, fractional_digits must consist of only one or more 0 digits, or the method returns false.
AllowExponent "E" 或 "E" 字元,表示指數標記法,以及exponential_digitsThe "e" or "E" character, which indicates exponential notation, along with exponential_digits. 如果 value 代表指數標記法中的數位,則不能有非零的小數部分。If value represents a number in exponential notation, it cannot have a non-zero, fractional component.
AllowLeadingWhite value開頭的ws元素。The ws element at the start of value.
AllowTrailingWhite value結尾的ws元素。The ws element at the end of value.
AllowLeadingSign 數位前面的正負號元素。The sign element before digits.
AllowTrailingSign 數位後面的sign元素。The sign element after digits.
AllowParentheses 以括弧形式括住數值的sign元素。The sign element in the form of parentheses enclosing the numeric value.
AllowThousands 群組分隔符號()元素。The group separator (,) element.
AllowCurrencySymbol Currency ($)元素。The currency ($) element.
Currency 所有元素。All elements. 不過,value 不能以指數標記法來表示十六進位數位或數位。However, value cannot represent a hexadecimal number or a number in exponential notation.
Float value開頭或結尾處的ws元素、value開頭和小數點(.)符號的符號The ws element at the start or end of value, sign at the start of value, and the decimal point (.) symbol. value 參數也可以使用指數標記法。The value parameter can also use exponential notation.
Number Wssign、group 分隔符號()和小數點(.)元素。The ws, sign, group separator (,), and decimal point (.) elements.
Any 所有元素。All elements. 不過,value 不能代表十六進位數位。However, value cannot represent a hexadecimal number.

重要

如果您使用 TryParse 方法來反復存取 ToString 方法所輸出之 BigInteger 值的字串表示,您應該使用 BigInteger.ToString(String) 方法搭配 "R" 格式規範,以產生 BigInteger 值的字串表示。If you use the TryParse method to round-trip the string representation of a BigInteger value that was output by the ToString method, you should use the BigInteger.ToString(String) method with the "R" format specifier to generate the string representation of the BigInteger value. 否則,BigInteger 的字串表示會保留原始值的50最有效位數,而當您使用 TryParse 方法還原 BigInteger 值時,資料可能會遺失。Otherwise, the string representation of the BigInteger preserves only the 50 most significant digits of the original value, and data may be lost when you use the TryParse method to restore the BigInteger value.

如果使用 NumberStyles.AllowHexSpecifier 旗標,value 必須是十六進位值。If the NumberStyles.AllowHexSpecifier flag is used, value must be a hexadecimal value. style 中唯一可以出現的其他旗標是 NumberStyles.AllowLeadingWhiteNumberStyles.AllowTrailingWhiteThe only other flags that can be present in style are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. NumberStyles 列舉具有同時包含空白字元旗標的複合樣式,HexNumber。)(The NumberStyles enumeration has a composite style, HexNumber, that includes both white-space flags.)

注意

如果 value 是十六進位數位的字串表示,其前面不能加上與十六進位數位區別的任何裝飾(例如 0x&h)。If value is the string representation of a hexadecimal number, it cannot be preceded by any decoration (such as 0x or &h) that differentiates it as a hexadecimal number. 這會導致轉換失敗。This causes the conversion to fail.

如果 value 是十六進位字串,則 TryParse(String, NumberStyles, IFormatProvider, BigInteger) 方法會使用兩個補數標記法,將 value 解讀為負數(如果其前兩個十六進位數位大於或等於 0x80)。If value is a hexadecimal string, the TryParse(String, NumberStyles, IFormatProvider, BigInteger) method interprets value as a negative number stored by using two's complement representation if its first two hexadecimal digits are greater than or equal to 0x80. 換句話說,方法會將 value 中第一個位元組的最高序位位解讀為符號位。In other words, the method interprets the highest-order bit of the first byte in value as the sign bit. 為確保十六進位字串正確地解讀為正數,value 中的第一個數位的值必須為零。To make sure that a hexadecimal string is correctly interpreted as a positive number, the first digit in value must have a value of zero. 例如,方法會將 0x80 解讀為負值,但它會將 0x0800x0080 解讀為正數值。For example, the method interprets 0x80 as a negative value, but it interprets either 0x080 or 0x0080 as a positive value. 下列範例說明代表負數值和正值的十六進位字串之間的差異。The following example illustrates the difference between hexadecimal strings that represent negative and positive values.

using System;
using System.Globalization;
using System.Numerics;

public class Example
{
   public static void Main()
   {
      string[] hexStrings = { "80", "E293", "F9A2FF", "FFFFFFFF", 
                              "080", "0E293", "0F9A2FF", "0FFFFFFFF",  
                              "0080", "00E293", "00F9A2FF", "00FFFFFFFF" };
      BigInteger number = BigInteger.Zero;
                              
      foreach (string hexString in hexStrings)
      {
         if (BigInteger.TryParse(hexString, NumberStyles.AllowHexSpecifier,
                                 null, out number))
            Console.WriteLine("Converted 0x{0} to {1}.", hexString, number);
         else
            Console.WriteLine("Cannot convert '{0}' to a BigInteger.", hexString);
      }
   }
}
// The example displays the following output:
//       Converted 0x80 to -128.
//       Converted 0xE293 to -7533.
//       Converted 0xF9A2FF to -417025.
//       Converted 0xFFFFFFFF to -1.
//       Converted 0x080 to 128.
//       Converted 0x0E293 to 58003.
//       Converted 0x0F9A2FF to 16360191.
//       Converted 0x0FFFFFFFF to 4294967295.
//       Converted 0x0080 to 128.
//       Converted 0x00E293 to 58003.
//       Converted 0x00F9A2FF to 16360191.
//       Converted 0x00FFFFFFFF to 4294967295.
Imports System.Globalization
Imports System.Numerics

Module Example
   Public Sub Main()
      Dim hexStrings() As String = { "80", "E293", "F9A2FF", "FFFFFFFF", 
                                     "080", "0E293", "0F9A2FF", "0FFFFFFFF",  
                                     "0080", "00E293", "00F9A2FF", "00FFFFFFFF" }
      Dim number As BigInteger = BigInteger.Zero
      
      For Each hexString As String In hexStrings
         If BigInteger.TryParse(hexString, NumberStyles.AllowHexSpecifier, 
                                Nothing, number) Then
            Console.WriteLine("Converted 0x{0} to {1}.", hexString, number)
         Else
            Console.WriteLine("Cannot convert '{0}' to a BigInteger.", hexString)
         End If
      Next         
   End Sub
End Module
' The example displays the following output:
'       Converted 0x80 to -128.
'       Converted 0xE293 to -7533.
'       Converted 0xF9A2FF to -417025.
'       Converted 0xFFFFFFFF to -1.
'       Converted 0x080 to 128.
'       Converted 0x0E293 to 58003.
'       Converted 0x0F9A2FF to 16360191.
'       Converted 0x0FFFFFFFF to 4294967295.
'       Converted 0x0080 to 128.
'       Converted 0x00E293 to 58003.
'       Converted 0x00F9A2FF to 16360191.
'       Converted 0x00FFFFFFFF to 4294967295.

provider 參數是 IFormatProvider 的實作為。The provider parameter is an IFormatProvider implementation. 它的 GetFormat 方法會傳回 NumberFormatInfo 物件,提供 value格式的特定文化特性資訊。Its GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of value. provider 參數可以是下列任何一項:The provider parameter can be any one of the following:

如果 null``provider,則會使用目前文化特性的 NumberFormatInfo 物件。If provider is null, the NumberFormatInfo object for the current culture is used.

另請參閱

適用於