UInt16.Parse Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Converte la rappresentazione di stringa di un numero nel suo equivalente intero senza segno a 16 bit.
Overload
Parse(String, NumberStyles, IFormatProvider) |
Converte la rappresentazione di stringa di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nell'equivalente intero senza segno a 16 bit. |
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) |
Converte la rappresentazione in forma di intervallo di un numero in uno stile e in un formato specifico delle impostazioni cultura specificati nell'equivalente intero senza segno a 16 bit. |
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider) |
Analizza un intervallo di caratteri UTF-8 in un valore. |
Parse(String, IFormatProvider) |
Converte la rappresentazione di stringa di un numero in un formato specifico delle impostazioni cultura nel suo equivalente intero senza segno a 16 bit. |
Parse(String, NumberStyles) |
Converte la rappresentazione di stringa di un numero in uno stile specificato nel suo equivalente intero senza segno a 16 bit. Questo metodo non è conforme a CLS. L'alternativa conforme a CLS è Parse(String, NumberStyles). |
Parse(ReadOnlySpan<Char>, IFormatProvider) |
Analizza un intervallo di caratteri in un valore. |
Parse(ReadOnlySpan<Byte>, IFormatProvider) |
Analizza un intervallo di caratteri UTF-8 in un valore. |
Parse(String) |
Converte la rappresentazione di stringa di un numero nel suo equivalente intero senza segno a 16 bit. |
Parse(String, NumberStyles, IFormatProvider)
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
Converte la rappresentazione di stringa di un numero in uno stile specificato e in un formato specifico delle impostazioni cultura nell'equivalente intero senza segno a 16 bit.
public:
static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::UInt16>::Parse;
[System.CLSCompliant(false)]
public static ushort Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static ushort Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static ushort Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint16
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As UShort
Parametri
- s
- String
Stringa che rappresenta il numero da convertire. La stringa viene interpretata usando lo stile specificato dal parametro style
.
- style
- NumberStyles
Combinazione bit per bit dei valori di enumerazione che indica gli elementi di stile che possono essere presenti in s
. Un valore tipico da specificare è Integer.
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relativamente a s
.
Restituisce
Intero senza segno a 16 bit equivalente al numero specificato in s
.
Implementazioni
- Attributi
Eccezioni
s
è null
.
style
non è un valore di NumberStyles.
-oppure-
style
non è una combinazione di valori di AllowHexSpecifier e HexNumber.
Il formato di s
non è conforme a style
.
s
rappresenta un numero minore di UInt16.MinValue o maggiore di UInt16.MaxValue.
-oppure-
s
include cifre frazionarie diverse da zero.
Esempio
Nell'esempio seguente viene usato il Parse(String, NumberStyles, IFormatProvider) metodo per convertire varie rappresentazioni di stringa di numeri in valori interi senza segno a 16 bit.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] cultureNames = { "en-US", "fr-FR" };
NumberStyles[] styles= { NumberStyles.Integer,
NumberStyles.Integer | NumberStyles.AllowDecimalPoint };
string[] values = { "1702", "+1702.0", "+1702,0", "-1032.00",
"-1032,00", "1045.1", "1045,1" };
// Parse strings using each culture
foreach (string cultureName in cultureNames)
{
CultureInfo ci = new CultureInfo(cultureName);
Console.WriteLine("Parsing strings using the {0} culture",
ci.DisplayName);
// Use each style.
foreach (NumberStyles style in styles)
{
Console.WriteLine(" Style: {0}", style.ToString());
// Parse each numeric string.
foreach (string value in values)
{
try {
Console.WriteLine(" Converted '{0}' to {1}.", value,
UInt16.Parse(value, style, ci));
}
catch (FormatException) {
Console.WriteLine(" Unable to parse '{0}'.", value);
}
catch (OverflowException) {
Console.WriteLine(" '{0}' is out of range of the UInt16 type.",
value);
}
}
}
}
}
}
// The example displays the following output:
// Parsing strings using the English (United States) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Converted '+1702.0' to 1702.
// Unable to parse '+1702,0'.
// '-1032.00' is out of range of the UInt16 type.
// Unable to parse '-1032,00'.
// '1045.1' is out of range of the UInt16 type.
// Unable to parse '1045,1'.
// Parsing strings using the French (France) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Converted '+1702,0' to 1702.
// Unable to parse '-1032.00'.
// '-1032,00' is out of range of the UInt16 type.
// Unable to parse '1045.1'.
// '1045,1' is out of range of the UInt16 type.
open System
open System.Globalization
let cultureNames = [| "en-US"; "fr-FR" |]
let styles =
[| NumberStyles.Integer; NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint |]
let values =
[| "1702"; "+1702.0"; "+1702,0"; "-1032.00"; "-1032,00"; "1045.1"; "1045,1" |]
// Parse strings using each culture
for cultureName in cultureNames do
let ci = CultureInfo cultureName
printfn $"Parsing strings using the {ci.DisplayName} culture"
// Use each style.
for style in styles do
printfn $" Style: {style}"
// Parse each numeric string.
for value in values do
try
printfn $" Converted '{value}' to {UInt16.Parse(value, style, ci)}."
with
| :? FormatException ->
printfn $" Unable to parse '{value}'."
| :? OverflowException ->
printfn $" '{value}' is out of range of the UInt16 type."
// The example displays the following output:
// Parsing strings using the English (United States) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Converted '+1702.0' to 1702.
// Unable to parse '+1702,0'.
// '-1032.00' is out of range of the UInt16 type.
// Unable to parse '-1032,00'.
// '1045.1' is out of range of the UInt16 type.
// Unable to parse '1045,1'.
// Parsing strings using the French (France) culture
// Style: Integer
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Unable to parse '+1702,0'.
// Unable to parse '-1032.00'.
// Unable to parse '-1032,00'.
// Unable to parse '1045.1'.
// Unable to parse '1045,1'.
// Style: Integer, AllowDecimalPoint
// Converted '1702' to 1702.
// Unable to parse '+1702.0'.
// Converted '+1702,0' to 1702.
// Unable to parse '-1032.00'.
// '-1032,00' is out of range of the UInt16 type.
// Unable to parse '1045.1'.
// '1045,1' is out of range of the UInt16 type.
Imports System.Globalization
Module Example
Public Sub Main()
Dim cultureNames() As String = { "en-US", "fr-FR" }
Dim styles() As NumberStyles = { NumberStyles.Integer, _
NumberStyles.Integer Or NumberStyles.AllowDecimalPoint }
Dim values() As String = { "1702", "+1702.0", "+1702,0", "-1032.00", _
"-1032,00", "1045.1", "1045,1" }
' Parse strings using each culture
For Each cultureName As String In cultureNames
Dim ci As New CultureInfo(cultureName)
Console.WriteLine("Parsing strings using the {0} culture", ci.DisplayName)
' Use each style.
For Each style As NumberStyles In styles
Console.WriteLine(" Style: {0}", style.ToString())
' Parse each numeric string.
For Each value As String In values
Try
Console.WriteLine(" Converted '{0}' to {1}.", value, _
UInt16.Parse(value, style, ci))
Catch e As FormatException
Console.WriteLine(" Unable to parse '{0}'.", value)
Catch e As OverflowException
Console.WriteLine(" '{0}' is out of range of the UInt16 type.", _
value)
End Try
Next
Next
Next
End Sub
End Module
' The example displays the following output:
' Parsing strings using the English (United States) culture
' Style: Integer
' Converted '1702' to 1702.
' Unable to parse '+1702.0'.
' Unable to parse '+1702,0'.
' Unable to parse '-1032.00'.
' Unable to parse '-1032,00'.
' Unable to parse '1045.1'.
' Unable to parse '1045,1'.
' Style: Integer, AllowDecimalPoint
' Converted '1702' to 1702.
' Converted '+1702.0' to 1702.
' Unable to parse '+1702,0'.
' '-1032.00' is out of range of the UInt16 type.
' Unable to parse '-1032,00'.
' '1045.1' is out of range of the UInt16 type.
' Unable to parse '1045,1'.
' Parsing strings using the French (France) culture
' Style: Integer
' Converted '1702' to 1702.
' Unable to parse '+1702.0'.
' Unable to parse '+1702,0'.
' Unable to parse '-1032.00'.
' Unable to parse '-1032,00'.
' Unable to parse '1045.1'.
' Unable to parse '1045,1'.
' Style: Integer, AllowDecimalPoint
' Converted '1702' to 1702.
' Unable to parse '+1702.0'.
' Converted '+1702,0' to 1702.
' Unable to parse '-1032.00'.
' '-1032,00' is out of range of the UInt16 type.
' Unable to parse '1045.1'.
' '1045,1' is out of range of the UInt16 type.
Commenti
Il style
parametro definisce gli elementi di stile ,ad esempio spazio vuoto o simbolo di segno positivo o negativo, consentiti nel s
parametro per l'operazione di analisi. Deve essere una combinazione di flag di bit dall'enumerazione NumberStyles .
A seconda del valore di style
, il s
parametro può includere gli elementi seguenti:
[ws] [$][sign]digits[.fractional_digits][E[sign]exponential_digits][ws]
Gli elementi tra parentesi quadre ([e]) sono facoltativi. Se style
include NumberStyles.AllowHexSpecifier, il s
parametro può includere gli elementi seguenti:
[ws] hexdigits[ws]
La tabella seguente descrive i singoli elementi.
Elemento | Descrizione |
---|---|
ws | Spazio vuoto facoltativo. Lo spazio vuoto può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingWhite flag e può essere visualizzato alla fine di s se style include il NumberStyles.AllowTrailingWhite flag.style |
$ | Simbolo di valuta specifico delle impostazioni cultura. La sua posizione nella stringa è definita dalla CurrencyPositivePattern proprietà dell'oggetto NumberFormatInfo restituito dal GetFormat metodo del provider parametro. Il simbolo di valuta può essere visualizzato in s se style include il NumberStyles.AllowCurrencySymbol flag. |
sign | Segno facoltativo. Il metodo genera un OverflowException se s include un segno negativo e rappresenta un numero diverso da zero. Il segno può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingSign flag e può apparire la fine di s se style include il NumberStyles.AllowTrailingSignstyle flag. Le parentesi possono essere usate in s per indicare un valore negativo se style include il NumberStyles.AllowParentheses flag. |
Cifre | Sequenza di cifre da 0 a 9. |
. | Simbolo decimale specifico delle impostazioni cultura. Il simbolo decimale della cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag. |
Cifre_frazionarie | Una o più occorrenze della cifra 0-9 se style include il NumberStyles.AllowExponent flag o una o più occorrenze della cifra 0 se non lo fa. Le cifre frazionarie possono essere visualizzate solo s se style include il NumberStyles.AllowDecimalPoint flag. |
E | Carattere "e" o "E", che indica che il valore è rappresentato nella notazione esponenziale (scientifica). Il s parametro può rappresentare un numero in notazione esponenziale se style include il NumberStyles.AllowExponent flag. |
exponential_digits | Sequenza di cifre da 0 a 9. Il s parametro può rappresentare un numero in notazione esponenziale se style include il NumberStyles.AllowExponent flag. |
hexdigits | Sequenza di cifre esadecimali da 0 a f o da 0 a F. |
Nota
Tutti i caratteri NUL terminanti (U+0000) vengono s
ignorati dall'operazione di analisi, indipendentemente dal valore dell'argomento style
.
Una stringa con cifre decimali (che corrisponde allo NumberStyles.None stile) analizza sempre correttamente. La maggior parte degli elementi di controllo dei membri rimanenti NumberStyles che possono essere presenti, ma non sono necessari, in questa stringa di input. La tabella seguente indica come i singoli NumberStyles membri influiscono sugli elementi che possono essere presenti in s
.
Valori non compositi NumberStyles |
Elementi consentiti oltre s alle cifre |
---|---|
NumberStyles.None | Solo cifre decimali. |
NumberStyles.AllowDecimalPoint | Elemento decimale (.) e fractional_digits . Tuttavia, se lo stile non include il NumberStyles.AllowExponent flag, fractional_digits deve essere costituito da una o più cifre. In caso contrario, viene generata un'eccezione OverflowException . |
NumberStyles.AllowExponent | Carattere "e" o "E", che indica la notazione esponenziale, insieme a exponential_digits. |
NumberStyles.AllowLeadingWhite | Elemento ws all'inizio di s . |
NumberStyles.AllowTrailingWhite | Elemento ws alla fine di s . |
NumberStyles.AllowLeadingSign | Segno prima delle cifre. |
NumberStyles.AllowTrailingSign | Segno dopo cifre. |
NumberStyles.AllowParentheses | Parentesi prima e dopo le cifre per indicare un valore negativo. |
NumberStyles.AllowThousands | Elemento separatore di gruppo (,). |
NumberStyles.AllowCurrencySymbol | Elemento currency ($). |
Se viene usato il NumberStyles.AllowHexSpecifier flag, s
deve essere un valore esadecimale. Le cifre esadecimali valide sono da 0 a 9, da f a F e da A a F. Un prefisso, ad esempio "0x", non è supportato e causa l'esito negativo dell'operazione di analisi. Gli unici flag che possono essere combinati con NumberStyles.AllowHexSpecifier sono NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. L'enumerazione NumberStyles include uno stile numero composito, , NumberStyles.HexNumberche include entrambi i flag di spazi vuoti.
Nota
Se il s
parametro è la rappresentazione stringa di un numero esadecimale, non può essere preceduto da alcuna decorazione (ad esempio 0x
o &h
) che la differenzia come numero esadecimale. In questo modo l'operazione di analisi genera un'eccezione.
Il provider
parametro è un'implementazione IFormatProvider il cui GetFormat metodo restituisce un NumberFormatInfo oggetto che fornisce informazioni specifiche delle impostazioni cultura sul formato di s
. Esistono tre modi per usare il provider
parametro per fornire informazioni di formattazione personalizzate all'operazione di analisi:
È possibile passare l'oggetto effettivo NumberFormatInfo che fornisce informazioni di formattazione. La sua implementazione di GetFormat restituisce semplicemente se stessa.
È possibile passare un CultureInfo oggetto che specifica le impostazioni cultura di cui utilizzare la formattazione. La proprietà NumberFormat fornisce informazioni di formattazione.
È possibile passare un'implementazione personalizzata IFormatProvider . Il metodo GetFormat deve creare un'istanza e restituire l'oggetto NumberFormatInfo che fornisce informazioni di formattazione.
Se provider
è null
, viene utilizzato l'oggetto NumberFormatInfo per le impostazioni cultura correnti.
Vedi anche
Si applica a
Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
Importante
Questa API non è conforme a CLS.
Converte la rappresentazione in forma di intervallo di un numero in uno stile e in un formato specifico delle impostazioni cultura specificati nell'equivalente intero senza segno a 16 bit.
public static ushort Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
[System.CLSCompliant(false)]
public static ushort Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
[System.CLSCompliant(false)]
public static ushort Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint16
[<System.CLSCompliant(false)>]
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UShort
Parametri
- s
- ReadOnlySpan<Char>
Intervallo contenente i caratteri che rappresentano il numero da convertire. L'intervallo viene interpretato usando lo stile specificato dal parametro style
.
- style
- NumberStyles
Combinazione bit per bit dei valori di enumerazione che indica gli elementi di stile che possono essere presenti in s
. Un valore tipico da specificare è Integer.
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relativamente a s
.
Restituisce
Intero senza segno a 16 bit equivalente al numero specificato in s
.
Implementazioni
- Attributi
Si applica a
Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
Analizza un intervallo di caratteri UTF-8 in un valore.
public static ushort Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> uint16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As UShort
Parametri
- utf8Text
- ReadOnlySpan<Byte>
Intervallo di caratteri UTF-8 da analizzare.
- style
- NumberStyles
Combinazione bit per bit di stili numerici che possono essere presenti in utf8Text
.
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a utf8Text
.
Restituisce
Risultato dell'analisi utf8Text
di .
Implementazioni
Si applica a
Parse(String, IFormatProvider)
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
Converte la rappresentazione di stringa di un numero in un formato specifico delle impostazioni cultura nel suo equivalente intero senza segno a 16 bit.
public:
static System::UInt16 Parse(System::String ^ s, IFormatProvider ^ provider);
public:
static System::UInt16 Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<System::UInt16>::Parse;
[System.CLSCompliant(false)]
public static ushort Parse (string s, IFormatProvider provider);
public static ushort Parse (string s, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static ushort Parse (string s, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * IFormatProvider -> uint16
static member Parse : string * IFormatProvider -> uint16
Public Shared Function Parse (s As String, provider As IFormatProvider) As UShort
Parametri
- s
- String
Stringa che rappresenta il numero da convertire.
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relativamente a s
.
Restituisce
Intero senza segno a 16 bit equivalente al numero specificato in s
.
Implementazioni
- Attributi
Eccezioni
s
è null
.
Il formato di s
non è corretto.
s
rappresenta un numero minore di UInt16.MinValue o maggiore di UInt16.MaxValue.
Esempio
L'esempio seguente crea un'istanza di impostazioni cultura personalizzate che usa due segni più (++) come segno positivo. Chiama quindi il Parse(String, IFormatProvider) metodo per analizzare una matrice di stringhe usando CultureInfo oggetti che rappresentano entrambe le impostazioni cultura personalizzate e le impostazioni cultura invarianti.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
// Define a custom culture that uses "++" as a positive sign.
CultureInfo ci = new CultureInfo("");
ci.NumberFormat.PositiveSign = "++";
// Create an array of cultures.
CultureInfo[] cultures = { ci, CultureInfo.InvariantCulture };
// Create an array of strings to parse.
string[] values = { "++1403", "-0", "+0", "+16034",
Int16.MinValue.ToString(), "14.0", "18012" };
// Parse the strings using each culture.
foreach (CultureInfo culture in cultures)
{
Console.WriteLine("Parsing with the '{0}' culture.", culture.Name);
foreach (string value in values)
{
try {
ushort number = UInt16.Parse(value, culture);
Console.WriteLine(" Converted '{0}' to {1}.", value, number);
}
catch (FormatException) {
Console.WriteLine(" The format of '{0}' is invalid.", value);
}
catch (OverflowException) {
Console.WriteLine(" '{0}' is outside the range of a UInt16 value.", value);
}
}
}
}
}
// The example displays the following output:
// Parsing with the culture.
// Converted '++1403' to 1403.
// Converted '-0' to 0.
// The format of '+0' is invalid.
// The format of '+16034' is invalid.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
// Parsing with the '' culture.
// The format of '++1403' is invalid.
// Converted '-0' to 0.
// Converted '+0' to 0.
// Converted '+16034' to 16034.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
open System
open System.Globalization
// Define a custom culture that uses "++" as a positive sign.
let ci = CultureInfo ""
ci.NumberFormat.PositiveSign <- "++"
// Create an array of cultures.
let cultures = [| ci; CultureInfo.InvariantCulture |]
// Create an array of strings to parse.
let values =
[| "++1403"; "-0"; "+0"; "+16034"
string Int16.MinValue; "14.0"; "18012" |]
// Parse the strings using each culture.
for culture in cultures do
printfn $"Parsing with the '{culture.Name}' culture."
for value in values do
try
let number = UInt16.Parse(value, culture)
printfn $" Converted '{value}' to {number}."
with
| :? FormatException ->
printfn $" The format of '{value}' is invalid."
| :? OverflowException ->
printfn $" '{value}' is outside the range of a UInt16 value."
// The example displays the following output:
// Parsing with the culture.
// Converted '++1403' to 1403.
// Converted '-0' to 0.
// The format of '+0' is invalid.
// The format of '+16034' is invalid.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
// Parsing with the '' culture.
// The format of '++1403' is invalid.
// Converted '-0' to 0.
// Converted '+0' to 0.
// Converted '+16034' to 16034.
// '-32768' is outside the range of a UInt16 value.
// The format of '14.0' is invalid.
// Converted '18012' to 18012.
Imports System.Globalization
Module Example
Public Sub Main()
' Define a custom culture that uses "++" as a positive sign.
Dim ci As CultureInfo = New CultureInfo("")
ci.NumberFormat.PositiveSign = "++"
' Create an array of cultures.
Dim cultures() As CultureInfo = { ci, CultureInfo.InvariantCulture }
' Create an array of strings to parse.
Dim values() As String = { "++1403", "-0", "+0", "+16034", _
Int16.MinValue.ToString(), "14.0", "18012" }
' Parse the strings using each culture.
For Each culture As CultureInfo In cultures
Console.WriteLine("Parsing with the '{0}' culture.", culture.Name)
For Each value As String In values
Try
Dim number As UShort = UInt16.Parse(value, culture)
Console.WriteLine(" Converted '{0}' to {1}.", value, number)
Catch e As FormatException
Console.WriteLine(" The format of '{0}' is invalid.", value)
Catch e As OverflowException
Console.WriteLine(" '{0}' is outside the range of a UInt16 value.", value)
End Try
Next
Next
End Sub
End Module
' The example displays the following output:
' Parsing with the culture.
' Converted '++1403' to 1403.
' Converted '-0' to 0.
' The format of '+0' is invalid.
' The format of '+16034' is invalid.
' '-32768' is outside the range of a UInt16 value.
' The format of '14.0' is invalid.
' Converted '18012' to 18012.
' Parsing with the '' culture.
' The format of '++1403' is invalid.
' Converted '-0' to 0.
' Converted '+0' to 0.
' Converted '+16034' to 16034.
' '-32768' is outside the range of a UInt16 value.
' The format of '14.0' is invalid.
' Converted '18012' to 18012.
Commenti
Il s
parametro contiene un numero di form:
[ws] [sign] digits[ws]
Gli elementi tra parentesi quadre ([ e ]) sono facoltativi. La tabella seguente descrive i singoli elementi.
Elemento | Descrizione |
---|---|
ws | Spazio vuoto facoltativo. |
segno | Segno facoltativo o segno negativo se s rappresenta il valore zero. |
Cifre | Sequenza di cifre compresa tra 0 e 9. |
Il parametro s viene interpretato usando lo NumberStyles.Integer stile . Oltre alle cifre decimali del valore byte, sono consentiti solo spazi iniziali e finali insieme a un segno iniziale. Se il segno negativo è presente, s
deve rappresentare un valore pari a zero o il metodo genera un'eccezione OverflowException. Per definire in modo esplicito gli elementi di stile insieme alle informazioni di formattazione specifiche delle impostazioni cultura che possono essere presenti in s
, usare il Parse(String, NumberStyles, IFormatProvider) metodo .
Il provider
parametro è un'implementazione IFormatProvider il cui GetFormat metodo restituisce un NumberFormatInfo oggetto che fornisce informazioni specifiche delle impostazioni cultura sul formato di s
. Esistono tre modi per usare il provider
parametro per fornire informazioni di formattazione personalizzate all'operazione di analisi:
È possibile passare l'oggetto effettivo NumberFormatInfo che fornisce informazioni di formattazione. La sua implementazione di GetFormat restituisce semplicemente se stessa.
È possibile passare un CultureInfo oggetto che specifica le impostazioni cultura di cui utilizzare la formattazione. La proprietà NumberFormat fornisce informazioni di formattazione.
È possibile passare un'implementazione personalizzata IFormatProvider . Il metodo GetFormat deve creare un'istanza e restituire l'oggetto NumberFormatInfo che fornisce informazioni di formattazione.
Se provider
è null
, viene utilizzato per NumberFormatInfo le impostazioni cultura correnti.
Vedi anche
Si applica a
Parse(String, NumberStyles)
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
Importante
Questa API non è conforme a CLS.
Converte la rappresentazione di stringa di un numero in uno stile specificato nel suo equivalente intero senza segno a 16 bit.
Questo metodo non è conforme a CLS. L'alternativa conforme a CLS è Parse(String, NumberStyles).
public:
static System::UInt16 Parse(System::String ^ s, System::Globalization::NumberStyles style);
[System.CLSCompliant(false)]
public static ushort Parse (string s, System.Globalization.NumberStyles style);
public static ushort Parse (string s, System.Globalization.NumberStyles style);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles -> uint16
static member Parse : string * System.Globalization.NumberStyles -> uint16
Public Shared Function Parse (s As String, style As NumberStyles) As UShort
Parametri
- s
- String
Stringa che rappresenta il numero da convertire. La stringa viene interpretata usando lo stile specificato dal parametro style
.
- style
- NumberStyles
Combinazione bit per bit dei valori di enumerazione che specifica il formato consentito di s
. Un valore tipico da specificare è Integer.
Restituisce
Intero senza segno a 16 bit equivalente al numero specificato in s
.
- Attributi
Eccezioni
s
è null
.
style
non è un valore di NumberStyles.
-oppure-
style
non è una combinazione di valori di AllowHexSpecifier e HexNumber.
Il formato di s
non è conforme a style
.
s
rappresenta un numero minore di UInt16.MinValue o maggiore di UInt16.MaxValue.
-oppure-
s
include cifre frazionarie diverse da zero.
Esempio
Nell'esempio seguente viene eseguito un tentativo di analizzare ogni elemento in una matrice di stringhe usando un numero di NumberStyles valori.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] values = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" };
NumberStyles whitespace = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite;
NumberStyles[] styles = { NumberStyles.None, whitespace,
NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | whitespace,
NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol,
NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint };
// Attempt to convert each number using each style combination.
foreach (string value in values)
{
Console.WriteLine("Attempting to convert '{0}':", value);
foreach (NumberStyles style in styles)
{
try {
ushort number = UInt16.Parse(value, style);
Console.WriteLine(" {0}: {1}", style, number);
}
catch (FormatException) {
Console.WriteLine(" {0}: Bad Format", style);
}
}
Console.WriteLine();
}
}
}
// The example display the following output:
// Attempting to convert ' 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: 214
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1,064':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: 1064
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '(0)':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1241+':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 1241
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' + 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' +214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '2153.0':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 2153
//
// Attempting to convert '1e03':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 1000
//
// Attempting to convert '1300.0e-2':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 13
open System
open System.Globalization
let values = [| " 214 "; "1,064"; "(0)"; "1241+"; " + 214 "; " +214 "; "2153.0"; "1e03"; "1300.0e-2" |]
let whitespace = NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite
let styles =
[| NumberStyles.None; whitespace
NumberStyles.AllowLeadingSign ||| NumberStyles.AllowTrailingSign ||| whitespace
NumberStyles.AllowThousands ||| NumberStyles.AllowCurrencySymbol
NumberStyles.AllowExponent ||| NumberStyles.AllowDecimalPoint |]
// Attempt to convert each number using each style combination.
for value in values do
printfn $"Attempting to convert '{value}':"
for style in styles do
try
let number = UInt16.Parse(value, style)
printfn $" {style}: {number}"
with :? FormatException ->
printfn $" {style}: Bad Format"
printfn ""
// The example display the following output:
// Attempting to convert ' 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: 214
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1,064':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: 1064
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '(0)':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '1241+':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 1241
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' + 214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert ' +214 ':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: 214
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: Bad Format
//
// Attempting to convert '2153.0':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 2153
//
// Attempting to convert '1e03':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 1000
//
// Attempting to convert '1300.0e-2':
// None: Bad Format
// AllowLeadingWhite, AllowTrailingWhite: Bad Format
// Integer, AllowTrailingSign: Bad Format
// AllowThousands, AllowCurrencySymbol: Bad Format
// AllowDecimalPoint, AllowExponent: 13
Imports System.Globalization
Module Example
Public Sub Main()
Dim values() As String = { " 214 ", "1,064", "(0)", "1241+", " + 214 ", " +214 ", "2153.0", "1e03", "1300.0e-2" }
Dim whitespace As NumberStyles = NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite
Dim styles() As NumberStyles = { NumberStyles.None, _
whitespace, _
NumberStyles.AllowLeadingSign Or NumberStyles.AllowTrailingSign Or whitespace, _
NumberStyles.AllowThousands Or NumberStyles.AllowCurrencySymbol, _
NumberStyles.AllowExponent Or NumberStyles.AllowDecimalPoint }
' Attempt to convert each number using each style combination.
For Each value As String In values
Console.WriteLine("Attempting to convert '{0}':", value)
For Each style As NumberStyles In styles
Try
Dim number As UShort = UInt16.Parse(value, style)
Console.WriteLine(" {0}: {1}", style, number)
Catch e As FormatException
Console.WriteLine(" {0}: Bad Format", style)
End Try
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' Attempting to convert ' 214 ':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: 214
' Integer, AllowTrailingSign: 214
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '1,064':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: 1064
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '(0)':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '1241+':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: 1241
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert ' + 214 ':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert ' +214 ':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: 214
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: Bad Format
'
' Attempting to convert '2153.0':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: 2153
'
' Attempting to convert '1e03':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: 1000
'
' Attempting to convert '1300.0e-2':
' None: Bad Format
' AllowLeadingWhite, AllowTrailingWhite: Bad Format
' Integer, AllowTrailingSign: Bad Format
' AllowThousands, AllowCurrencySymbol: Bad Format
' AllowDecimalPoint, AllowExponent: 13
Commenti
Il style
parametro definisce gli elementi di stile ,ad esempio lo spazio vuoto, il simbolo di segno positivo o negativo, il simbolo separatore di gruppo o il simbolo di virgola decimale consentiti nel s
parametro per l'esito positivo dell'operazione di analisi.
style
deve essere una combinazione di flag di bit dell'enumerazione NumberStyles . Il style
parametro rende utile questo overload del metodo quando s
contiene la rappresentazione di stringa di un valore esadecimale, quando il sistema numerico (decimale o esadecimale) rappresentato da s
è noto solo in fase di esecuzione o quando si desidera impedire lo spazio vuoto o un simbolo di segno in s
.
A seconda del valore di style
, il s
parametro può includere gli elementi seguenti:
[ws] [$][sign][digits,]digits[.fractional_digits][E[sign]exponential_digits][ws]
Gli elementi tra parentesi quadre ([e]) sono facoltativi. Se style
include NumberStyles.AllowHexSpecifier, il s
parametro può contenere gli elementi seguenti:
[ws] hexdigits[ws]
La tabella seguente descrive i singoli elementi.
Elemento | Descrizione |
---|---|
ws | Spazio vuoto facoltativo. Lo spazio vuoto può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingWhite flag e può essere visualizzato alla fine di s se style include il NumberStyles.AllowTrailingWhite flag .style |
$ | Simbolo di valuta specifico delle impostazioni cultura. La posizione nella stringa è definita dalle NumberFormatInfo.CurrencyNegativePattern proprietà e NumberFormatInfo.CurrencyPositivePattern delle impostazioni cultura correnti. Il simbolo di valuta delle impostazioni cultura correnti può essere visualizzato in s se style include il NumberStyles.AllowCurrencySymbol flag . |
sign | Segno facoltativo. Il segno può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingSign flag e può essere visualizzato alla fine di s se style include il NumberStyles.AllowTrailingSignstyle flag . Le parentesi possono essere usate in s per indicare un valore negativo se style include il NumberStyles.AllowParentheses flag . Tuttavia, il simbolo del segno negativo può essere usato solo con zero; in caso contrario, il metodo genera un'eccezione OverflowException. |
Cifre Cifre_frazionarie exponential_digits |
Sequenza di cifre da 0 a 9. Per fractional_digits, solo la cifra 0 è valida. |
, | Simbolo separatore di gruppi specifico delle impostazioni cultura. Il separatore di gruppo delle impostazioni cultura correnti può essere visualizzato in s se style include il NumberStyles.AllowThousands flag . |
. | Simbolo decimale specifico delle impostazioni cultura. Il simbolo decimale della cultura corrente può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag. Solo la cifra 0 può essere visualizzata come cifra frazionaria per l'esito positivo dell'operazione di analisi; se fractional_digits include qualsiasi altra cifra, viene generata una FormatException classe. |
E | Carattere "e" o "E", che indica che il valore è rappresentato nella notazione esponenziale (scientifica). Il s parametro può rappresentare un numero in notazione esponenziale se style include il NumberStyles.AllowExponent flag. |
hexdigits | Sequenza di cifre esadecimali da 0 a f o da 0 a F. |
Nota
Tutti i caratteri NUL terminanti (U+0000) vengono s
ignorati dall'operazione di analisi, indipendentemente dal valore dell'argomento style
.
Una stringa con cifre solo (che corrisponde allo NumberStyles.None stile) analizza sempre correttamente se si trova nell'intervallo del UInt16 tipo. La maggior parte degli elementi di controllo dei membri rimanenti NumberStyles che possono essere presenti, ma non devono essere presenti nella stringa di input. La tabella seguente indica come i singoli NumberStyles membri influiscono sugli elementi che possono essere presenti in s
.
Valore della proprietà NumberStyles |
Elementi consentiti oltre s alle cifre |
---|---|
None | Solo l'elemento cifre . |
AllowDecimalPoint | Elementi decimali (.) e cifre frazionarie . |
AllowExponent | Carattere "e" o "E", che indica la notazione esponenziale, insieme a exponential_digits. |
AllowLeadingWhite | Elemento ws all'inizio di s . |
AllowTrailingWhite | Elemento ws alla fine di s . |
AllowLeadingSign | Elemento di segno all'inizio di s . |
AllowTrailingSign | Elemento di segno alla fine di s . |
AllowParentheses | Elemento di segno sotto forma di parentesi che racchiude il valore numerico. |
AllowThousands | Elemento separatore di gruppo (,). |
AllowCurrencySymbol | Elemento currency ($). |
Currency | Tutti gli elementi. Tuttavia, s non può rappresentare un numero esadecimale o un numero in notazione esponenziale. |
Float | Elemento ws all'inizio o alla fine di s , segno all'inizio di s e il simbolo decimale (.). Il s parametro può anche usare la notazione esponenziale. |
Number | Elementi ws , , sign separatore di gruppo (,) e decimale (.). |
Any | Tutti gli elementi. Tuttavia, s non può rappresentare un numero esadecimale. |
A differenza degli altri NumberStyles valori, che consentono, ma non richiedono, la presenza di elementi di stile specifici in , il NumberStyles.AllowHexSpecifier valore dello stile significa che i singoli caratteri numerici in s
s
vengono sempre interpretati come caratteri esadecimali. I caratteri esadecimali validi sono 0-9, A-F e a-f. Un prefisso, ad esempio "0x", non è supportato e causa l'esito negativo dell'operazione di analisi. Gli unici flag che possono essere combinati con il style
parametro sono NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. L'enumerazione NumberStyles include uno stile numero composito, , NumberStyles.HexNumberche include entrambi i flag di spazi vuoti.
Nota
Se s
è la rappresentazione stringa di un numero esadecimale, non può essere preceduta da alcuna decorazione (ad esempio 0x
o &h
) che la differenzia come numero esadecimale. In questo modo la conversione ha esito negativo.
Il s
parametro viene analizzato usando le informazioni di formattazione in un NumberFormatInfo oggetto inizializzato per le impostazioni cultura di sistema correnti. Per specificare le impostazioni cultura le cui informazioni di formattazione vengono usate per l'operazione di analisi, chiamare l'overload Parse(String, NumberStyles, IFormatProvider) .
Vedi anche
Si applica a
Parse(ReadOnlySpan<Char>, IFormatProvider)
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
Analizza un intervallo di caratteri in un valore.
public:
static System::UInt16 Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::UInt16>::Parse;
public static ushort Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> uint16
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As UShort
Parametri
- s
- ReadOnlySpan<Char>
Intervallo di caratteri da analizzare.
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a s
.
Restituisce
Risultato dell'analisi s
di .
Implementazioni
Si applica a
Parse(ReadOnlySpan<Byte>, IFormatProvider)
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
Analizza un intervallo di caratteri UTF-8 in un valore.
public:
static System::UInt16 Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<System::UInt16>::Parse;
public static ushort Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> uint16
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As UShort
Parametri
- utf8Text
- ReadOnlySpan<Byte>
Intervallo di caratteri UTF-8 da analizzare.
- provider
- IFormatProvider
Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a utf8Text
.
Restituisce
Risultato dell'analisi utf8Text
di .
Implementazioni
Si applica a
Parse(String)
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
- Origine:
- UInt16.cs
Converte la rappresentazione di stringa di un numero nel suo equivalente intero senza segno a 16 bit.
public:
static System::UInt16 Parse(System::String ^ s);
[System.CLSCompliant(false)]
public static ushort Parse (string s);
public static ushort Parse (string s);
[<System.CLSCompliant(false)>]
static member Parse : string -> uint16
static member Parse : string -> uint16
Public Shared Function Parse (s As String) As UShort
Parametri
- s
- String
Stringa che rappresenta il numero da convertire.
Restituisce
Intero senza segno a 16 bit equivalente al numero contenuto in s
.
- Attributi
Eccezioni
s
è null
.
Il formato di s
non è corretto.
s
rappresenta un numero minore di UInt16.MinValue o maggiore di UInt16.MaxValue.
Esempio
Nell'esempio seguente viene chiamato il Parse(String) metodo per convertire ogni elemento in una matrice di stringhe in un intero senza segno a 16 bit.
using System;
public class Example
{
public static void Main()
{
string[] values = { "-0", "17", "-12", "185", "66012", "+0",
"", null, "16.1", "28.0", "1,034" };
foreach (string value in values)
{
try {
ushort number = UInt16.Parse(value);
Console.WriteLine("'{0}' --> {1}", value, number);
}
catch (FormatException) {
Console.WriteLine("'{0}' --> Bad Format", value);
}
catch (OverflowException) {
Console.WriteLine("'{0}' --> OverflowException", value);
}
catch (ArgumentNullException) {
Console.WriteLine("'{0}' --> Null", value);
}
}
}
}
// The example displays the following output:
// '-0' --> 0
// '17' --> 17
// '-12' --> OverflowException
// '185' --> 185
// '66012' --> OverflowException
// '+0' --> 0
// '' --> Bad Format
// '' --> Null
// '16.1' --> Bad Format
// '28.0' --> Bad Format
// '1,034' --> Bad Format
open System
let values =
[| "-0"; "17"; "-12"; "185"; "66012"; "+0"
""; null; "16.1"; "28.0"; "1,034" |]
for value in values do
try
let number = UInt16.Parse value
printfn $"'{value}' --> {number}"
with
| :? FormatException ->
printfn $"'{value}' --> Bad Format"
| :? OverflowException ->
printfn $"'{value}' --> OverflowException"
| :? ArgumentNullException ->
printfn $"'{value}' --> Null"
// The example displays the following output:
// '-0' --> 0
// '17' --> 17
// '-12' --> OverflowException
// '185' --> 185
// '66012' --> OverflowException
// '+0' --> 0
// '' --> Bad Format
// '' --> Null
// '16.1' --> Bad Format
// '28.0' --> Bad Format
// '1,034' --> Bad Format
Module Example
Public Sub Main()
Dim values() As String = { "-0", "17", "-12", "185", "66012", _
"+0", "", Nothing, "16.1", "28.0", _
"1,034" }
For Each value As String In values
Try
Dim number As UShort = UInt16.Parse(value)
Console.WriteLine("'{0}' --> {1}", value, number)
Catch e As FormatException
Console.WriteLine("'{0}' --> Bad Format", value)
Catch e As OverflowException
Console.WriteLine("'{0}' --> OverflowException", value)
Catch e As ArgumentNullException
Console.WriteLine("'{0}' --> Null", value)
End Try
Next
End Sub
End Module
' The example displays the following output:
' '-0' --> 0
' '17' --> 17
' '-12' --> OverflowException
' '185' --> 185
' '66012' --> OverflowException
' '+0' --> 0
' '' --> Bad Format
' '' --> Null
' '16.1' --> Bad Format
' '28.0' --> Bad Format
' '1,034' --> Bad Format
Commenti
Il s
parametro deve essere la rappresentazione stringa di un numero nel formato seguente.
[ws] [sign] cifre[ws]
Gli elementi tra parentesi quadre ([e]) sono facoltativi. La tabella seguente descrive i singoli elementi.
Elemento | Descrizione |
---|---|
ws | Spazio vuoto facoltativo. |
sign | Segno facoltativo. I caratteri di segno validi sono determinati dalle NumberFormatInfo.NegativeSign proprietà e NumberFormatInfo.PositiveSign delle impostazioni cultura correnti. Tuttavia, il simbolo di segno negativo può essere usato solo con zero; in caso contrario, il metodo genera un OverflowExceptionoggetto . |
Cifre | Sequenza di cifre compreso tra 0 e 9. Gli zero iniziali vengono ignorati. |
Nota
La stringa specificata dal s
parametro viene interpretata usando lo NumberStyles.Integer stile. Non può contenere separatori di gruppo o separatori decimali e non può avere una parte decimale.
Il s
parametro viene analizzato usando le informazioni di formattazione in un System.Globalization.NumberFormatInfo oggetto inizializzato per le impostazioni cultura di sistema correnti. Per altre informazioni, vedere NumberFormatInfo.CurrentInfo. Per analizzare una stringa usando le informazioni di formattazione di una cultura specifica, usare il Parse(String, IFormatProvider) metodo .
Vedi anche
Si applica a
Commenti e suggerimenti
https://aka.ms/ContentUserFeedback.
Presto disponibile: Nel corso del 2024 verranno gradualmente disattivati i problemi di GitHub come meccanismo di feedback per il contenuto e ciò verrà sostituito con un nuovo sistema di feedback. Per altre informazioni, vedereInvia e visualizza il feedback per