Byte.TryParse Metodo

Definizione

Prova a convertire la rappresentazione di stringa di un numero nell'oggetto Byte equivalente e restituisce un valore che indica se la conversione è stata eseguita correttamente.

Overload

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Byte)

Prova a analizzare un intervallo di caratteri UTF-8 in un valore.

TryParse(ReadOnlySpan<Char>, Byte)

Prova a convertire la rappresentazione intervallo di un numero nell'oggetto Byte equivalente e restituisce un valore che indica se la conversione è stata eseguita correttamente.

TryParse(String, Byte)

Prova a convertire la rappresentazione di stringa di un numero nell'oggetto Byte equivalente e restituisce un valore che indica se la conversione è stata eseguita correttamente.

TryParse(ReadOnlySpan<Char>, IFormatProvider, Byte)

Prova a analizzare un intervallo di caratteri in un valore.

TryParse(String, IFormatProvider, Byte)

Prova a analizzare una stringa in un valore.

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Byte)

Prova a analizzare un intervallo di caratteri UTF-8 in un valore.

TryParse(ReadOnlySpan<Byte>, Byte)

Tenta di convertire un intervallo di caratteri UTF-8 contenente la rappresentazione stringa di un numero nell'equivalente intero senza segno a 8 bit.

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

Converte la rappresentazione in forma di intervallo di un numero in uno stile specificato e un formato specifico delle impostazioni cultura indicato nel valore Byte equivalente. Un valore restituito indica se la conversione è riuscita o meno.

TryParse(String, NumberStyles, IFormatProvider, Byte)

Converte la rappresentazione di stringa di un numero in uno stile specificato e un formato specifico delle impostazioni cultura indicato nell'oggetto Byte equivalente. Un valore restituito indica se la conversione è riuscita o meno.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Byte)

Source:
Byte.cs
Source:
Byte.cs

Prova a analizzare un intervallo di caratteri UTF-8 in un valore.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Byte % result) = IUtf8SpanParsable<System::Byte>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out byte result);
static member TryParse : ReadOnlySpan<byte> * IFormatProvider * byte -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider, ByRef result As Byte) As Boolean

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.

result
Byte

In caso di restituzione, contiene il risultato dell'analisi utf8Text corretta o di un valore non definito in caso di errore.

Restituisce

true se è stato analizzato correttamente; in caso utf8Text contrario, false.

Si applica a

TryParse(ReadOnlySpan<Char>, Byte)

Source:
Byte.cs
Source:
Byte.cs
Source:
Byte.cs

Prova a convertire la rappresentazione intervallo di un numero nell'oggetto Byte equivalente e restituisce un valore che indica se la conversione è stata eseguita correttamente.

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

Parametri

s
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano il numero da convertire.

result
Byte

Quando questo metodo restituisce un risultato, contiene il valore di Byte equivalente al numero contenuto in s se la conversione riesce oppure zero se la conversione non riesce. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result verrà sovrascritto.

Restituisce

true se s è stato convertito correttamente; in caso contrario, false.

Si applica a

TryParse(String, Byte)

Source:
Byte.cs
Source:
Byte.cs
Source:
Byte.cs

Prova a convertire la rappresentazione di stringa di un numero nell'oggetto Byte equivalente e restituisce un valore che indica se la conversione è stata eseguita correttamente.

public:
 static bool TryParse(System::String ^ s, [Runtime::InteropServices::Out] System::Byte % result);
public static bool TryParse (string s, out byte result);
public static bool TryParse (string? s, out byte result);
static member TryParse : string * byte -> bool
Public Shared Function TryParse (s As String, ByRef result As Byte) As Boolean

Parametri

s
String

Stringa contenente un numero da convertire.

result
Byte

Quando questo metodo restituisce un risultato, contiene il valore di Byte equivalente al numero contenuto in s se la conversione riesce oppure zero se la conversione non riesce. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result verrà sovrascritto.

Restituisce

true se s è stato convertito correttamente; in caso contrario, false.

Esempio

Nell'esempio seguente viene chiamato il TryParse(String, Byte) metodo con un numero di valori stringa diversi.

using namespace System;

void main()
{
   array<String^>^ byteStrings = gcnew array<String^> { nullptr, String::Empty, 
                                                        "1024", "100.1", "100", 
                                                        "+100", "-100", "000000000000000100", 
                                                        "00,100", "   20   ", "FF", "0x1F" };
   Byte byteValue;
   for each (String^ byteString in byteStrings) {
      bool result = Byte::TryParse(byteString, byteValue);
      if (result)
         Console::WriteLine("Converted '{0}' to {1}", 
                            byteString, byteValue);
      else
         Console::WriteLine("Attempted conversion of '{0}' failed.", 
                            byteString);
   }
}
// The example displays the following output:
//       Attempted conversion of '' failed.
//       Attempted conversion of '' failed.`
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Attempted conversion of '00,100' failed.
//       Converted '   20   ' to 20
//       Attempted conversion of 'FF' failed.
//       Attempted conversion of '0x1F' failed.}
using System;

public class ByteConversion
{
   public static void Main()
   {
      string[] byteStrings = { null, string.Empty, "1024",
                               "100.1", "100", "+100", "-100",
                               "000000000000000100", "00,100",
                               "   20   ", "FF", "0x1F" };

      foreach (var byteString in byteStrings)
      {
          CallTryParse(byteString);
      }
   }

   private static void CallTryParse(string stringToConvert)
   {
      byte byteValue;
      bool success = Byte.TryParse(stringToConvert, out byteValue);
      if (success)
      {
         Console.WriteLine("Converted '{0}' to {1}",
                        stringToConvert, byteValue);
      }
      else
      {
         Console.WriteLine("Attempted conversion of '{0}' failed.",
                           stringToConvert);
      }
   }
}
// The example displays the following output to the console:
//       Attempted conversion of '' failed.
//       Attempted conversion of '' failed.
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Attempted conversion of '00,100' failed.
//       Converted '   20   ' to 20
//       Attempted conversion of 'FF' failed.
//       Attempted conversion of '0x1F' failed.
open System

let callTryParse (stringToConvert: string) =
    match Byte.TryParse stringToConvert with
    | true, byteValue ->
        printfn $"Converted '{stringToConvert}' to {byteValue}"
    | _ ->
        printfn $"Attempted conversion of '{stringToConvert}' failed."

let byteStrings = 
    [ null; String.Empty; "1024"
      "100.1"; "100"; "+100"; "-100"
      "000000000000000100"; "00,100"
      "   20   "; "FF"; "0x1F" ]

for byteString in byteStrings do
    callTryParse byteString

// The example displays the following output to the console:
//       Attempted conversion of '' failed.
//       Attempted conversion of '' failed.
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Attempted conversion of '00,100' failed.
//       Converted '   20   ' to 20
//       Attempted conversion of 'FF' failed.
//       Attempted conversion of '0x1F' failed.
Module ByteConversion
   Public Sub Main()
      Dim byteStrings() As String = { Nothing, String.Empty, "1024", 
                                    "100.1", "100", "+100", "-100",
                                    "000000000000000100", "00,100",
                                    "   20   ", "FF", "0x1F"}

      For Each byteString As String In byteStrings
        CallTryParse(byteString)
      Next
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String)  
      Dim byteValue As Byte
      Dim success As Boolean = Byte.TryParse(stringToConvert, byteValue)
      If success Then
         Console.WriteLine("Converted '{0}' to {1}", _
                        stringToConvert, byteValue)
      Else
         Console.WriteLine("Attempted conversion of '{0}' failed.", _
                           stringToConvert)
      End If                        
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversion of '' failed.
'       Attempted conversion of '' failed.
'       Attempted conversion of '1024' failed.
'       Attempted conversion of '100.1' failed.
'       Converted '100' to 100
'       Converted '+100' to 100
'       Attempted conversion of '-100' failed.
'       Converted '000000000000000100' to 100
'       Attempted conversion of '00,100' failed.
'       Converted '   20   ' to 20
'       Attempted conversion of 'FF' failed.
'       Attempted conversion of '0x1F' failed.

Commenti

La conversione ha esito negativo e il metodo restituisce se il s parametro non è nel formato corretto, se è null o oppure String.Emptyse rappresenta un numero minore MinValue o maggiore di MaxValue.false

Il Byte.TryParse(String, Byte) metodo è simile al Byte.Parse(String) metodo, ad eccezione del fatto che TryParse(String, Byte) non genera un'eccezione se la conversione ha esito negativo.

Il s parametro deve essere la rappresentazione stringa di un numero nel formato seguente:

[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.
sign Segno positivo facoltativo, come specificato dalla NumberFormatInfo.PositiveSign proprietà delle impostazioni cultura correnti.
Cifre Sequenza di cifre decimali comprese tra 0 e 9.

Il s parametro viene interpretato usando lo Integer stile. Oltre alle cifre decimali del valore di byte, sono consentiti solo spazi iniziali e finali insieme a un segno iniziale. Se il segno è presente, deve essere un segno positivo o il metodo genera un OverflowExceptionoggetto .) 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 Byte.Parse(String, NumberStyles, IFormatProvider) metodo .

Il s parametro viene analizzato usando le informazioni di formattazione in un NumberFormatInfo oggetto per le impostazioni cultura correnti. Per altre informazioni, vedere NumberFormatInfo.CurrentInfo.

Questo overload del Byte.TryParse(String, Byte) metodo interpreta tutte le cifre nel s parametro come cifre decimali. Per analizzare la rappresentazione stringa di un numero esadecimale, chiamare l'overload Byte.TryParse(String, NumberStyles, IFormatProvider, Byte) .

Vedi anche

Si applica a

TryParse(ReadOnlySpan<Char>, IFormatProvider, Byte)

Source:
Byte.cs
Source:
Byte.cs
Source:
Byte.cs

Prova a analizzare un intervallo di caratteri in un valore.

public:
 static bool TryParse(ReadOnlySpan<char> s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Byte % result) = ISpanParsable<System::Byte>::TryParse;
public static bool TryParse (ReadOnlySpan<char> s, IFormatProvider? provider, out byte result);
static member TryParse : ReadOnlySpan<char> * IFormatProvider * byte -> bool
Public Shared Function TryParse (s As ReadOnlySpan(Of Char), provider As IFormatProvider, ByRef result As Byte) As Boolean

Parametri

s
ReadOnlySpan<Char>

Intervallo di caratteri da analizzare.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a s.

result
Byte

Quando questo metodo restituisce, contiene il risultato dell'analisi sdi o un valore non definito in caso di errore.

Restituisce

true se è stato analizzato correttamente; in caso s contrario, false.

Si applica a

TryParse(String, IFormatProvider, Byte)

Source:
Byte.cs
Source:
Byte.cs
Source:
Byte.cs

Prova a analizzare una stringa in un valore.

public:
 static bool TryParse(System::String ^ s, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Byte % result) = IParsable<System::Byte>::TryParse;
public static bool TryParse (string? s, IFormatProvider? provider, out byte result);
static member TryParse : string * IFormatProvider * byte -> bool
Public Shared Function TryParse (s As String, provider As IFormatProvider, ByRef result As Byte) As Boolean

Parametri

s
String

Stringa da analizzare.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a s.

result
Byte

Quando questo metodo restituisce, contiene il risultato dell'analisi s corretta o di un valore non definito in caso di errore.

Restituisce

true se è stato analizzato correttamente; in caso s contrario, false.

Si applica a

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, Byte)

Source:
Byte.cs
Source:
Byte.cs

Prova a analizzare un intervallo di caratteri UTF-8 in un valore.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, System::Globalization::NumberStyles style, IFormatProvider ^ provider, [Runtime::InteropServices::Out] System::Byte % result) = System::Numerics::INumberBase<System::Byte>::TryParse;
public static bool TryParse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out byte result);
static member TryParse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider * byte -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), style As NumberStyles, provider As IFormatProvider, ByRef result As Byte) As Boolean

Parametri

utf8Text
ReadOnlySpan<Byte>

Intervallo di caratteri UTF-8 da analizzare.

style
NumberStyles

Combinazione bit per bit di stili di numero che possono essere presenti in utf8Text.

provider
IFormatProvider

Oggetto che fornisce informazioni di formattazione specifiche delle impostazioni cultura relative a utf8Text.

result
Byte

In caso di restituzione, contiene il risultato dell'analisi utf8Text corretta o di un valore non definito in caso di errore.

Restituisce

true se è stato analizzato correttamente; in caso utf8Text contrario, false.

Si applica a

TryParse(ReadOnlySpan<Byte>, Byte)

Source:
Byte.cs
Source:
Byte.cs

Tenta di convertire un intervallo di caratteri UTF-8 contenente la rappresentazione stringa di un numero nell'equivalente intero senza segno a 8 bit.

public:
 static bool TryParse(ReadOnlySpan<System::Byte> utf8Text, [Runtime::InteropServices::Out] System::Byte % result);
public static bool TryParse (ReadOnlySpan<byte> utf8Text, out byte result);
static member TryParse : ReadOnlySpan<byte> * byte -> bool
Public Shared Function TryParse (utf8Text As ReadOnlySpan(Of Byte), ByRef result As Byte) As Boolean

Parametri

utf8Text
ReadOnlySpan<Byte>

Intervallo contenente i caratteri UTF-8 che rappresentano il numero da convertire.

result
Byte

Quando questo metodo viene restituito, contiene il valore intero senza segno a 8 bit equivalente al numero contenuto in utf8Text, se la conversione riesce oppure zero se la conversione non riesce. Questo parametro viene passato non inizializzato. Qualsiasi valore specificato in origine in result verrà sovrascritto.

Restituisce

true se utf8Text è stato convertito correttamente; in caso contrario, false.

Si applica a

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

Source:
Byte.cs
Source:
Byte.cs
Source:
Byte.cs

Converte la rappresentazione in forma di intervallo di un numero in uno stile specificato e un formato specifico delle impostazioni cultura indicato nel valore Byte equivalente. Un valore restituito indica se la conversione è riuscita o meno.

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

Parametri

s
ReadOnlySpan<Char>

Intervallo contenente i caratteri che rappresentano il numero da convertire. Per interpretare l'intervallo, viene usato lo stile Integer.

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. Se provider è null, verranno usate le impostazioni cultura correnti del thread.

result
Byte

Quando questo metodo viene restituito, contiene il valore intero senza segno a 8 bit equivalente al numero contenuto in s, se la conversione riesce oppure zero se la conversione non riesce. La conversione ha esito negativo se il s parametro è o Empty, non è null del formato corretto o rappresenta un numero minore di Byte.MinValue o maggiore di Byte.MaxValue. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result verrà sovrascritto.

Restituisce

true se s è stato convertito correttamente; in caso contrario, false.

Si applica a

TryParse(String, NumberStyles, IFormatProvider, Byte)

Source:
Byte.cs
Source:
Byte.cs
Source:
Byte.cs

Converte la rappresentazione di stringa di un numero in uno stile specificato e un formato specifico delle impostazioni cultura indicato nell'oggetto Byte equivalente. Un valore restituito indica se la conversione è riuscita o meno.

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

Parametri

s
String

Stringa che contiene un numero da convertire. La stringa viene interpreta usando lo stile specificato da 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. Se provider è null, verranno usate le impostazioni cultura correnti del thread.

result
Byte

Quando questo metodo viene restituito, contiene il valore intero senza segno a 8 bit equivalente al numero contenuto in s, se la conversione riesce oppure zero se la conversione non riesce. La conversione ha esito negativo se il s parametro è null o Empty, non è del formato corretto oppure rappresenta un numero minore di Byte.MinValue o maggiore di Byte.MaxValue. Questo parametro viene passato non inizializzato. Qualsiasi valore fornito in origine in result verrà sovrascritto.

Restituisce

true se s è stato convertito correttamente; in caso contrario, false.

Eccezioni

style non è un valore di NumberStyles.

-oppure-

style non è una combinazione di valori di AllowHexSpecifier e HexNumber.

Esempio

Nell'esempio seguente viene chiamato il TryParse(String, NumberStyles, IFormatProvider, Byte) metodo con un numero di valori stringa diversi.

using namespace System;
using namespace System::Globalization;

void CallTryParse(String^ byteString, NumberStyles styles);

void main()
{
   String^ byteString; 
   NumberStyles styles;

   byteString = "1024";
   styles = NumberStyles::Integer;
   CallTryParse(byteString, styles);

   byteString = "100.1";
   styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
   CallTryParse(byteString, styles);

   byteString = "100.0";
   CallTryParse(byteString, styles);

   byteString = "+100";
   styles = NumberStyles::Integer | NumberStyles::AllowLeadingSign 
            | NumberStyles::AllowTrailingSign;
   CallTryParse(byteString, styles);

   byteString = "-100";
   CallTryParse(byteString, styles);

   byteString = "000000000000000100";
   CallTryParse(byteString, styles);

   byteString = "00,100";
   styles = NumberStyles::Integer | NumberStyles::AllowThousands;
   CallTryParse(byteString, styles);

   byteString = "2E+3   ";
   styles = NumberStyles::Integer | NumberStyles::AllowExponent;
   CallTryParse(byteString, styles);

   byteString = "FF";
   styles = NumberStyles::HexNumber;
   CallTryParse(byteString, styles);

   byteString = "0x1F";
   CallTryParse(byteString, styles);
}

void CallTryParse(String^ stringToConvert, NumberStyles styles)
{  
   Byte byteValue;
   bool result = Byte::TryParse(stringToConvert, styles, 
                                 (IFormatProvider^) nullptr , byteValue);
   if (result)
      Console::WriteLine("Converted '{0}' to {1}", 
                     stringToConvert, byteValue);
   else
      Console::WriteLine("Attempted conversion of '{0}' failed.", 
                        stringToConvert);
}
// The example displays the following output:
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100.0' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Converted '00,100' to 100
//       Attempted conversion of '2E+3   ' failed.
//       Converted 'FF' to 255
//       Attempted conversion of '0x1F' failed.}
using System;
using System.Globalization;

public class ByteConversion2
{
   public static void Main()
   {
      string byteString;
      NumberStyles styles;

      byteString = "1024";
      styles = NumberStyles.Integer;
      CallTryParse(byteString, styles);

      byteString = "100.1";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(byteString, styles);

      byteString = "100.0";
      CallTryParse(byteString, styles);

      byteString = "+100";
      styles = NumberStyles.Integer | NumberStyles.AllowLeadingSign
               | NumberStyles.AllowTrailingSign;
      CallTryParse(byteString, styles);

      byteString = "-100";
      CallTryParse(byteString, styles);

      byteString = "000000000000000100";
      CallTryParse(byteString, styles);

      byteString = "00,100";
      styles = NumberStyles.Integer | NumberStyles.AllowThousands;
      CallTryParse(byteString, styles);

      byteString = "2E+3   ";
      styles = NumberStyles.Integer | NumberStyles.AllowExponent;
      CallTryParse(byteString, styles);

      byteString = "FF";
      styles = NumberStyles.HexNumber;
      CallTryParse(byteString, styles);

      byteString = "0x1F";
      CallTryParse(byteString, styles);
   }

   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {
      Byte byteValue;
      bool result = Byte.TryParse(stringToConvert, styles,
                                  null as IFormatProvider, out byteValue);
      if (result)
         Console.WriteLine("Converted '{0}' to {1}",
                        stringToConvert, byteValue);
      else
         Console.WriteLine("Attempted conversion of '{0}' failed.",
                           stringToConvert.ToString());
   }
}
// The example displays the following output to the console:
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100.0' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Converted '00,100' to 100
//       Attempted conversion of '2E+3   ' failed.
//       Converted 'FF' to 255
//       Attempted conversion of '0x1F' failed.
open System
open System.Globalization

let callTryParse (stringToConvert: string) (styles: NumberStyles) =
    match Byte.TryParse(stringToConvert, styles, null) with
    | true, byteValue ->
        printfn $"Converted '{stringToConvert}' to {byteValue}"
    | _ ->
        printfn $"Attempted conversion of '{stringToConvert}' failed."
                        
[<EntryPoint>]
let main _ =
    let byteString = "1024"
    let styles = NumberStyles.Integer
    callTryParse byteString styles

    let byteString = "100.1"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowDecimalPoint
    callTryParse byteString styles

    let byteString = "100.0"
    callTryParse byteString styles

    let byteString = "+100"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowLeadingSign ||| NumberStyles.AllowTrailingSign
    callTryParse byteString styles

    let byteString = "-100"
    callTryParse byteString styles

    let byteString = "000000000000000100"
    callTryParse byteString styles

    let byteString = "00,100"
    let styles = NumberStyles.Integer ||| NumberStyles.AllowThousands
    callTryParse byteString styles

    let byteString = "2E+3   "
    let styles = NumberStyles.Integer ||| NumberStyles.AllowExponent
    callTryParse byteString styles

    let byteString = "FF"
    let styles = NumberStyles.HexNumber
    callTryParse byteString styles

    let byteString = "0x1F"
    callTryParse byteString styles

    0

// The example displays the following output to the console:
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100.0' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Converted '00,100' to 100
//       Attempted conversion of '2E+3   ' failed.
//       Converted 'FF' to 255
//       Attempted conversion of '0x1F' failed.
Imports System.Globalization

Module ByteConversion2
   Public Sub Main()
      Dim byteString As String 
      Dim styles As NumberStyles
      
      byteString = "1024"
      styles = NumberStyles.Integer
      CallTryParse(byteString, styles)
      
      byteString = "100.1"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(byteString, styles)
      
      byteString = "100.0"
      CallTryParse(byteString, styles)
      
      byteString = "+100"
      styles = NumberStyles.Integer Or NumberStyles.AllowLeadingSign _
               Or NumberStyles.AllowTrailingSign
      CallTryParse(byteString, styles)
      
      byteString = "-100"
      CallTryParse(byteString, styles)
      
      byteString = "000000000000000100"
      CallTryParse(byteString, styles)
      
      byteString = "00,100"      
      styles = NumberStyles.Integer Or NumberStyles.AllowThousands
      CallTryParse(byteString, styles)
      
      byteString = "2E+3   "
      styles = NumberStyles.Integer Or NumberStyles.AllowExponent
      CallTryParse(byteString, styles)
      
      byteString = "FF"
      styles = NumberStyles.HexNumber
      CallTryParse(byteString, styles)
      
      byteString = "0x1F"
      CallTryParse(byteString, styles)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String, styles As NumberStyles)  
      Dim byteValue As Byte
      Dim result As Boolean = Byte.TryParse(stringToConvert, styles, Nothing, _
                                            byteValue)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}", _
                        stringToConvert, byteValue)
      Else
         If stringToConvert Is Nothing Then stringToConvert = ""
         Console.WriteLine("Attempted conversion of '{0}' failed.", _
                           stringToConvert.ToString())
      End If                        
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversion of '1024' failed.
'       Attempted conversion of '100.1' failed.
'       Converted '100.0' to 100
'       Converted '+100' to 100
'       Attempted conversion of '-100' failed.
'       Converted '000000000000000100' to 100
'       Converted '00,100' to 100
'       Attempted conversion of '2E+3   ' failed.
'       Converted 'FF' to 255
'       Attempted conversion of '0x1F' failed.

Commenti

Il TryParse metodo è simile al Parse metodo , ad eccezione del fatto che il TryParse metodo non genera un'eccezione se la conversione non riesce.

Il s parametro viene analizzato usando le informazioni di formattazione in un NumberFormatInfo oggetto fornito dal provider parametro .

Il parametro style definisce gli elementi di stile (ad esempio lo spazio vuoto o il segno positivo) consentiti nel s parametro per l'esito positivo dell'operazione di analisi. Deve essere una combinazione di flag di bit dell'enumerazione NumberStyles . A seconda del valore di style, il s parametro può includere gli elementi seguenti:

[ws] [$] [sign]digits[.fractional_digits][e[sign]digits][ws]

In alternativa, se il style parametro include AllowHexSpecifier:

[ws]hexdigits[ws]

Gli elementi tra parentesi quadre ( [ e ] ) sono facoltativi. 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 o alla fine di s se lo stile include il NumberStyles.AllowTrailingWhitestyle flag.
$ Simbolo di valuta specifico delle impostazioni cultura. La posizione nella stringa è definita dalla NumberFormatInfo.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 positivo facoltativo. L'operazione di analisi ha esito negativo se è presente un segno negativo in s. Il segno può essere visualizzato all'inizio di s se include il NumberStyles.AllowLeadingSign flag o alla fine di s se style include il NumberStyles.AllowTrailingSign flag .style
Cifre Sequenza di cifre da 0 a 9.
. Simbolo di virgola decimale specifica delle impostazioni cultura. Il simbolo di virgola decimale delle impostazioni cultura specificate da provider può essere visualizzato in s se style include il NumberStyles.AllowDecimalPoint flag .
Cifre_frazionarie Una o più occorrenze della cifra 0. 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 in notazione esponenziale. 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

Qualsiasi carattere NUL di terminazione (U+0000) in s viene ignorato dall'operazione di analisi, indipendentemente dal valore dell'argomento style .

Una stringa con solo cifre decimali (che corrisponde allo NumberStyles.None stile) analizza sempre correttamente. La maggior parte degli elementi di controllo membri rimanenti NumberStyles che possono essere ma non devono essere presenti in questa stringa di input. La tabella seguente indica in che modo i singoli NumberStyles membri influiscono sugli elementi che possono essere presenti in s.

Valori NumberStyles non compositi Elementi consentiti in s oltre alle cifre
NumberStyles.None Solo cifre decimali.
NumberStyles.AllowDecimalPoint Elementi . e fractional_digits . Tuttavia, fractional_digits deve essere costituito da una o più cifre 0 oppure il metodo restituisce false.
NumberStyles.AllowExponent Il s parametro può anche usare la notazione esponenziale. Se s rappresenta un numero in notazione esponenziale, deve rappresentare un numero intero all'interno dell'intervallo del Byte tipo di dati senza un componente frazionaria diverso da zero.
NumberStyles.AllowLeadingWhite Elemento ws all'inizio di s.
NumberStyles.AllowTrailingWhite Elemento ws alla fine di s.
NumberStyles.AllowLeadingSign Un segno positivo può essere visualizzato prima delle cifre.
NumberStyles.AllowTrailingSign Un segno positivo può essere visualizzato dopo le cifre.
NumberStyles.AllowParentheses Anche se questo flag è supportato, il metodo restituisce false se le parentesi sono presenti in s.
NumberStyles.AllowThousands Anche se il simbolo separatore di gruppo può essere visualizzato in s, può essere preceduto da una o più cifre 0.
NumberStyles.AllowCurrencySymbol Elemento $.

Se viene usato il NumberStyles.AllowHexSpecifier flag, s deve essere un valore esadecimale senza un prefisso. Ad esempio, "F3" analizza correttamente, ma "0xF3" non. Gli unici flag che possono essere presenti in style sono NumberStyles.AllowLeadingWhite e NumberStyles.AllowTrailingWhite. L'enumerazione NumberStyles ha uno stile numerico composito, NumberStyles.HexNumber, che include entrambi i flag di spazio vuoto.

Il provider parametro è un'implementazione IFormatProvider , ad esempio un CultureInfo oggetto o un NumberFormatInfo oggetto , il cui GetFormat metodo restituisce un NumberFormatInfo oggetto . L'oggetto NumberFormatInfo fornisce informazioni specifiche delle impostazioni cultura sul formato di s.

Vedi anche

Si applica a