Boolean Struct

Definizione

Rappresenta un valore booleano (true o false).

public value class bool : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
public value class bool : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>, IParsable<bool>, ISpanParsable<bool>
public value class bool : IComparable, IConvertible
public value class bool : IComparable, IComparable<bool>, IEquatable<bool>
public struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
public readonly struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
public readonly struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>, IParsable<bool>, ISpanParsable<bool>
[System.Serializable]
public struct Boolean : IComparable, IConvertible
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
public struct Boolean : IComparable, IComparable<bool>, IEquatable<bool>
type bool = struct
    interface IConvertible
type bool = struct
    interface IConvertible
    interface IParsable<bool>
    interface ISpanParsable<bool>
[<System.Serializable>]
type bool = struct
    interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type bool = struct
    interface IConvertible
type bool = struct
Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IConvertible, IEquatable(Of Boolean)
Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IConvertible, IEquatable(Of Boolean), IParsable(Of Boolean), ISpanParsable(Of Boolean)
Public Structure Boolean
Implements IComparable, IConvertible
Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IEquatable(Of Boolean)
Ereditarietà
Boolean
Attributi
Implementazioni

Commenti

Un'istanza Boolean può avere uno dei due valori: true o false.

La Boolean struttura fornisce metodi che supportano le attività seguenti:

Le sezioni seguenti illustrano queste attività e altri dettagli sull'utilizzo:

Formattare i valori booleani

La rappresentazione stringa di un Boolean oggetto è "True" per un true valore o "False" per un false valore. La rappresentazione stringa di un Boolean valore è definita dai campi e FalseString di sola TrueString lettura.

Usare il ToString metodo per convertire i valori booleani in stringhe. La struttura booleana include due ToString overload: il metodo senza ToString() parametri e il metodo, che include un parametro che controlla la ToString(IFormatProvider) formattazione. Tuttavia, poiché questo parametro viene ignorato, i due overload producono stringhe identiche. Il ToString(IFormatProvider) metodo non supporta la formattazione sensibile alle impostazioni cultura.

Nell'esempio seguente viene illustrata la formattazione con il ToString metodo . Si noti che gli esempi C# e VB usano la funzionalità di formattazione composita , mentre l'esempio F# usa l'interpolazione delle stringhe. In entrambi i casi il ToString metodo viene chiamato in modo implicito.

using System;

public class Example
{
   public static void Main()
   {
      bool raining = false;
      bool busLate = true;

      Console.WriteLine("It is raining: {0}", raining);
      Console.WriteLine("The bus is late: {0}", busLate);
   }
}
// The example displays the following output:
//       It is raining: False
//       The bus is late: True
let raining = false
let busLate = true

printfn $"It is raining: {raining}"
printfn $"The bus is late: {busLate}"

// The example displays the following output:
//       It is raining: False
//       The bus is late: True
Module Example
   Public Sub Main()
      Dim raining As Boolean = False
      Dim busLate As Boolean = True

      Console.WriteLine("It is raining: {0}", raining)
      Console.WriteLine("The bus is late: {0}", busLate)
   End Sub
End Module
' The example displays the following output:
'       It is raining: False
'       The bus is late: True

Poiché la Boolean struttura può avere solo due valori, è facile aggiungere formattazione personalizzata. Per la formattazione personalizzata semplice in cui altri valori letterali stringa vengono sostituiti per "True" e "False", è possibile usare qualsiasi funzionalità di valutazione condizionale supportata dal linguaggio, ad esempio l'operatore condizionale in C# o l'operatore If in Visual Basic. Nell'esempio seguente viene usata questa tecnica per formattare Boolean i valori come "Sì" e "No" anziché "True" e "False".

using System;

public class Example
{
   public static void Main()
   {
      bool raining = false;
      bool busLate = true;

      Console.WriteLine("It is raining: {0}",
                        raining ? "Yes" : "No");
      Console.WriteLine("The bus is late: {0}",
                        busLate ? "Yes" : "No" );
   }
}
// The example displays the following output:
//       It is raining: No
//       The bus is late: Yes
Module Example
   Public Sub Main()
      Dim raining As Boolean = False
      Dim busLate As Boolean = True

      Console.WriteLine("It is raining: {0}", 
                        If(raining, "Yes", "No"))
      Console.WriteLine("The bus is late: {0}", 
                        If(busLate, "Yes", "No"))
   End Sub
End Module
' The example displays the following output:
'       It is raining: No
'       The bus is late: Yes
let raining = false
let busLate = true

printfn $"""It is raining: %s{if raining then "Yes" else "No"}"""
printfn $"""The bus is late: %s{if busLate then "Yes" else "No"}"""

// The example displays the following output:
//       It is raining: No
//       The bus is late: Yes

Per operazioni di formattazione personalizzate più complesse, inclusa la formattazione sensibile alle impostazioni cultura, è possibile chiamare il String.Format(IFormatProvider, String, Object[]) metodo e fornire un'implementazione ICustomFormatter . Nell'esempio seguente vengono implementate le ICustomFormatter interfacce e IFormatProvider per fornire stringhe booleane sensibili alle impostazioni cultura per le impostazioni cultura (Stati Uniti), le impostazioni cultura francese (Francia) e russo (Russia).

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      String[] cultureNames = { "", "en-US", "fr-FR", "ru-RU" };
      foreach (var cultureName in cultureNames) {
         bool value = true;
         CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
         BooleanFormatter formatter = new BooleanFormatter(culture);

         string result = string.Format(formatter, "Value for '{0}': {1}", culture.Name, value);
         Console.WriteLine(result);
      }
   }
}

public class BooleanFormatter : ICustomFormatter, IFormatProvider
{
   private CultureInfo culture;

   public BooleanFormatter() : this(CultureInfo.CurrentCulture)
   { }

   public BooleanFormatter(CultureInfo culture)
   {
      this.culture = culture;
   }

   public Object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }

   public string Format(string fmt, Object arg, IFormatProvider formatProvider)
   {
      // Exit if another format provider is used.
      if (! formatProvider.Equals(this)) return null;

      // Exit if the type to be formatted is not a Boolean
      if (! (arg is Boolean)) return null;

      bool value = (bool) arg;
      switch (culture.Name) {
         case "en-US":
            return value.ToString();
         case "fr-FR":
            if (value)
               return "vrai";
            else
               return "faux";
         case "ru-RU":
            if (value)
               return "верно";
            else
               return "неверно";
         default:
            return value.ToString();
      }
   }
}
// The example displays the following output:
//       Value for '': True
//       Value for 'en-US': True
//       Value for 'fr-FR': vrai
//       Value for 'ru-RU': верно
open System
open System.Globalization

type BooleanFormatter(culture) =
    interface ICustomFormatter with
        member this.Format(_, arg, formatProvider) =
            if formatProvider <> this then null
            else
                match arg with
                | :? bool as value -> 
                    match culture.Name with 
                    | "en-US" -> string arg
                    | "fr-FR" when value -> "vrai"
                    | "fr-FR" -> "faux"
                    | "ru-RU" when value -> "верно"
                    | "ru-RU" -> "неверно"
                    | _ -> string arg
                | _ -> null
    interface IFormatProvider with
        member this.GetFormat(formatType) =
            if formatType = typeof<ICustomFormatter> then this
            else null
    new() = BooleanFormatter CultureInfo.CurrentCulture

let cultureNames = [ ""; "en-US"; "fr-FR"; "ru-RU" ]
for cultureName in cultureNames do
    let value = true
    let culture = CultureInfo.CreateSpecificCulture cultureName 
    let formatter = BooleanFormatter culture

    String.Format(formatter, "Value for '{0}': {1}", culture.Name, value)
    |> printfn "%s"

// The example displays the following output:
//       Value for '': True
//       Value for 'en-US': True
//       Value for 'fr-FR': vrai
//       Value for 'ru-RU': верно
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "", "en-US", "fr-FR", "ru-RU" }
      For Each cultureName In cultureNames
         Dim value As Boolean = True
         Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureName)
         Dim formatter As New BooleanFormatter(culture)
         
         Dim result As String = String.Format(formatter, "Value for '{0}': {1}", culture.Name, value)
         Console.WriteLine(result)
      Next
   End Sub
End Module

Public Class BooleanFormatter 
   Implements ICustomFormatter, IFormatProvider
   
   Private culture As CultureInfo
   
   Public Sub New()
      Me.New(CultureInfo.CurrentCulture)
   End Sub
   
   Public Sub New(culture As CultureInfo)
      Me.culture = culture 
   End Sub
   
   Public Function GetFormat(formatType As Type) As Object _
                   Implements IFormatProvider.GetFormat
      If formatType Is GetType(ICustomFormatter) Then
         Return Me
      Else
         Return Nothing
      End If                
   End Function
   
   Public Function Format(fmt As String, arg As Object, 
                          formatProvider As IFormatProvider) As String _
                   Implements ICustomFormatter.Format
      ' Exit if another format provider is used.
      If Not formatProvider.Equals(Me) Then Return Nothing
      
      ' Exit if the type to be formatted is not a Boolean
      If Not TypeOf arg Is Boolean Then Return Nothing
      
      Dim value As Boolean = CBool(arg)
      Select culture.Name
         Case "en-US"
            Return value.ToString()
         Case "fr-FR"
            If value Then
               Return "vrai"
            Else
               Return "faux"
            End If      
         Case "ru-RU"
            If value Then
               Return "верно"
            Else
               Return "неверно"
            End If   
         Case Else
            Return value.ToString()  
      End Select
   End Function
End Class
' The example displays the following output:
'          Value for '': True
'          Value for 'en-US': True
'          Value for 'fr-FR': vrai
'          Value for 'ru-RU': верно

Facoltativamente, è possibile usare i file di risorse per definire stringhe booleane specifiche delle impostazioni cultura.

Convertire in e da valori booleani

La Boolean struttura implementa l'interfaccia IConvertible . Di conseguenza, è possibile usare la Convert classe per eseguire conversioni tra un Boolean valore e qualsiasi altro tipo primitivo in .NET oppure chiamare Boolean le implementazioni esplicite della struttura. Tuttavia, le conversioni tra un Boolean e i tipi seguenti non sono supportate, pertanto i metodi di conversione corrispondenti generano un'eccezione InvalidCastException :

Tutte le conversioni da numeri integrali o a virgola mobile a valori booleani convertano valori non zero in true e zero valori in false. L'esempio seguente illustra questa operazione chiamando gli overload selezionati della Convert.ToBoolean classe.

using System;

public class Example
{
   public static void Main()
   {
      Byte byteValue = 12;
      Console.WriteLine(Convert.ToBoolean(byteValue));
      Byte byteValue2 = 0;
      Console.WriteLine(Convert.ToBoolean(byteValue2));
      int intValue = -16345;
      Console.WriteLine(Convert.ToBoolean(intValue));
      long longValue = 945;
      Console.WriteLine(Convert.ToBoolean(longValue));
      SByte sbyteValue = -12;
      Console.WriteLine(Convert.ToBoolean(sbyteValue));
      double dblValue = 0;
      Console.WriteLine(Convert.ToBoolean(dblValue));
      float sngValue = .0001f;
      Console.WriteLine(Convert.ToBoolean(sngValue));
   }
}
// The example displays the following output:
//       True
//       False
//       True
//       True
//       True
//       False
//       True
open System

let byteValue = 12uy
printfn $"{Convert.ToBoolean byteValue}"
let byteValue2 = 0uy
printfn $"{Convert.ToBoolean byteValue2}"
let intValue = -16345
printfn $"{Convert.ToBoolean intValue}"
let longValue = 945L
printfn $"{Convert.ToBoolean longValue}"
let sbyteValue = -12y
printfn $"{Convert.ToBoolean sbyteValue}"
let dblValue = 0.0
printfn $"{Convert.ToBoolean dblValue}"
let sngValue = 0.0001f
printfn $"{Convert.ToBoolean sngValue}"

// The example displays the following output:
//       True
//       False
//       True
//       True
//       True
//       False
//       True
Module Example
   Public Sub Main()
      Dim byteValue As Byte = 12
      Console.WriteLine(Convert.ToBoolean(byteValue))
      Dim byteValue2 As Byte = 0
      Console.WriteLine(Convert.ToBoolean(byteValue2))
      Dim intValue As Integer = -16345
      Console.WriteLine(Convert.ToBoolean(intValue))
      Dim longValue As Long = 945
      Console.WriteLine(Convert.ToBoolean(longValue))
      Dim sbyteValue As SByte = -12
      Console.WriteLine(Convert.ToBoolean(sbyteValue))
      Dim dblValue As Double = 0
      Console.WriteLine(Convert.ToBoolean(dblValue))
      Dim sngValue As Single = .0001
      Console.WriteLine(Convert.ToBoolean(sngValue))
   End Sub
End Module
' The example displays the following output:
'       True
'       False
'       True
'       True
'       True
'       False
'       True

Quando si converte da Boolean a valori numerici, i metodi di conversione della Convert classe vengono convertiti true in 1 e false in 0. Tuttavia, le funzioni di conversione di Visual Basic vengono convertite true in 255 (per le conversioni in Byte valori) o -1 (per tutte le altre conversioni numeriche). Nell'esempio seguente viene convertito in valori numerici true usando un Convert metodo e, nel caso dell'esempio di Visual Basic, usando l'operatore di conversione del linguaggio Visual Basic.

using System;

public class Example
{
   public static void Main()
   {
      bool flag = true;

      byte byteValue;
      byteValue = Convert.ToByte(flag);
      Console.WriteLine("{0} -> {1}", flag, byteValue);

      sbyte sbyteValue;
      sbyteValue = Convert.ToSByte(flag);
      Console.WriteLine("{0} -> {1}", flag, sbyteValue);

      double dblValue;
      dblValue = Convert.ToDouble(flag);
      Console.WriteLine("{0} -> {1}", flag, dblValue);

      int intValue;
      intValue = Convert.ToInt32(flag);
      Console.WriteLine("{0} -> {1}", flag, intValue);
   }
}
// The example displays the following output:
//       True -> 1
//       True -> 1
//       True -> 1
//       True -> 1
open System

let flag = true

let byteValue = Convert.ToByte flag
printfn $"{flag} -> {byteValue}"

let sbyteValue = Convert.ToSByte flag
printfn $"{flag} -> {sbyteValue}"

let dblValue = Convert.ToDouble flag
printfn $"{flag} -> {dblValue}"

let intValue = Convert.ToInt32(flag);
printfn $"{flag} -> {intValue}"

// The example displays the following output:
//       True -> 1
//       True -> 1
//       True -> 1
//       True -> 1
Module Example
   Public Sub Main()
      Dim flag As Boolean = true
      
      Dim byteValue As Byte   
      byteValue = Convert.ToByte(flag)
      Console.WriteLine("{0} -> {1} ({2})", flag, byteValue, 
                                            byteValue.GetType().Name)         
      byteValue = CByte(flag)
      Console.WriteLine("{0} -> {1} ({2})", flag, byteValue, 
                                            byteValue.GetType().Name)         
      
      Dim sbyteValue As SByte
      sbyteValue = Convert.ToSByte(flag)
      Console.WriteLine("{0} -> {1} ({2})", flag, sbyteValue, 
                                            sbyteValue.GetType().Name)         
      sbyteValue = CSByte(flag)
      Console.WriteLine("{0} -> {1} ({2})", flag, sbyteValue, 
                                            sbyteValue.GetType().Name)         

      Dim dblValue As Double
      dblValue = Convert.ToDouble(flag)
      Console.WriteLine("{0} -> {1} ({2})", flag, dblValue, 
                                            dblValue.GetType().Name)         
      dblValue = CDbl(flag)
      Console.WriteLine("{0} -> {1} ({2})", flag, dblValue, 
                                            dblValue.GetType().Name)         

      Dim intValue As Integer
      intValue = Convert.ToInt32(flag)
      Console.WriteLine("{0} -> {1} ({2})", flag, intValue, 
                                            intValue.GetType().Name)         
      intValue = CInt(flag)
      Console.WriteLine("{0} -> {1} ({2})", flag, intValue, 
                                            intValue.GetType().Name)         
   End Sub
End Module
' The example displays the following output:
'       True -> 1 (Byte)
'       True -> 255 (Byte)
'       True -> 1 (SByte)
'       True -> -1 (SByte)
'       True -> 1 (Double)
'       True -> -1 (Double)
'       True -> 1 (Int32)
'       True -> -1 (Int32)

Per le conversioni da Boolean a valori stringa, vedere la sezione Formattazione valori booleani . Per le conversioni da stringhe a Boolean valori, vedere la sezione Analisi dei valori booleani .

Analizzare i valori booleani

La Boolean struttura include due metodi Parse di analisi statica e TryParse, che converte una stringa in un valore booleano. La rappresentazione di stringa di un valore booleano è definita rispettivamente dagli equivalenti senza distinzione tra maiuscole e minuscoli dei valori e TrueStringFalseString , rispettivamente, "True" e "False". In altre parole, le uniche stringhe che analizzano correttamente sono "True", "False", "true", "false" o un equivalente misto-case. Non è possibile analizzare correttamente le stringhe numeriche, ad esempio "0" o "1". Gli spazi vuoti iniziali o finali non vengono considerati durante l'esecuzione del confronto tra stringhe.

Nell'esempio seguente vengono usati i Parse metodi e TryParse per analizzare un numero di stringhe. Si noti che è possibile analizzare correttamente solo gli equivalenti senza maiuscole e minuscole di "True" e "False".

using System;

public class Example
{
   public static void Main()
   {
      string[] values = { null, String.Empty, "True", "False",
                          "true", "false", "    true    ",
                           "TrUe", "fAlSe", "fa lse", "0",
                          "1", "-1", "string" };
      // Parse strings using the Boolean.Parse method.
      foreach (var value in values) {
         try {
            bool flag = Boolean.Parse(value);
            Console.WriteLine("'{0}' --> {1}", value, flag);
         }
         catch (ArgumentException) {
            Console.WriteLine("Cannot parse a null string.");
         }
         catch (FormatException) {
            Console.WriteLine("Cannot parse '{0}'.", value);
         }
      }
      Console.WriteLine();
      // Parse strings using the Boolean.TryParse method.
      foreach (var value in values) {
         bool flag = false;
         if (Boolean.TryParse(value, out flag))
            Console.WriteLine("'{0}' --> {1}", value, flag);
         else
            Console.WriteLine("Unable to parse '{0}'", value);
      }
   }
}
// The example displays the following output:
//       Cannot parse a null string.
//       Cannot parse ''.
//       'True' --> True
//       'False' --> False
//       'true' --> True
//       'false' --> False
//       '    true    ' --> True
//       'TrUe' --> True
//       'fAlSe' --> False
//       Cannot parse 'fa lse'.
//       Cannot parse '0'.
//       Cannot parse '1'.
//       Cannot parse '-1'.
//       Cannot parse 'string'.
//
//       Unable to parse ''
//       Unable to parse ''
//       'True' --> True
//       'False' --> False
//       'true' --> True
//       'false' --> False
//       '    true    ' --> True
//       'TrUe' --> True
//       'fAlSe' --> False
//       Cannot parse 'fa lse'.
//       Unable to parse '0'
//       Unable to parse '1'
//       Unable to parse '-1'
//       Unable to parse 'string'
open System

let values = 
    [ null; String.Empty; "True"; "False"
      "true"; "false"; "    true    "
      "TrUe"; "fAlSe"; "fa lse"; "0"
      "1"; "-1"; "string" ]
// Parse strings using the Boolean.Parse method.
for value in values do
    try
        let flag = Boolean.Parse value
        printfn $"'{value}' --> {flag}"
    with 
    | :? ArgumentException ->
        printfn "Cannot parse a null string."
    | :? FormatException ->
        printfn $"Cannot parse '{value}'."
printfn ""
// Parse strings using the Boolean.TryParse method.
for value in values do
    match Boolean.TryParse value with
    | true, flag -> 
        printfn $"'{value}' --> {flag}"
    | false, _ ->
        printfn $"Unable to parse '{value}'"

// The example displays the following output:
//       Cannot parse a null string.
//       Cannot parse ''.
//       'True' --> True
//       'False' --> False
//       'true' --> True
//       'false' --> False
//       '    true    ' --> True
//       'TrUe' --> True
//       'fAlSe' --> False
//       Cannot parse 'fa lse'.
//       Cannot parse '0'.
//       Cannot parse '1'.
//       Cannot parse '-1'.
//       Cannot parse 'string'.
//
//       Unable to parse ''
//       Unable to parse ''
//       'True' --> True
//       'False' --> False
//       'true' --> True
//       'false' --> False
//       '    true    ' --> True
//       'TrUe' --> True
//       'fAlSe' --> False
//       Cannot parse 'fa lse'.
//       Unable to parse '0'
//       Unable to parse '1'
//       Unable to parse '-1'
//       Unable to parse 'string'
Module Example
   Public Sub Main()
      Dim values() As String = { Nothing, String.Empty, "True", "False", 
                                 "true", "false", "    true    ", 
                                 "TrUe", "fAlSe", "fa lse", "0", 
                                 "1", "-1", "string" }
      ' Parse strings using the Boolean.Parse method.                    
      For Each value In values
         Try
            Dim flag As Boolean = Boolean.Parse(value)
            Console.WriteLine("'{0}' --> {1}", value, flag)
         Catch e As ArgumentException
            Console.WriteLine("Cannot parse a null string.")
         Catch e As FormatException
            Console.WriteLine("Cannot parse '{0}'.", value)
         End Try         
      Next  
      Console.WriteLine()
      ' Parse strings using the Boolean.TryParse method.                    
      For Each value In values
         Dim flag As Boolean = False
         If Boolean.TryParse(value, flag)
            Console.WriteLine("'{0}' --> {1}", value, flag)
         Else
            Console.WriteLine("Cannot parse '{0}'.", value)
         End If         
      Next  
   End Sub
End Module
' The example displays the following output:
'       Cannot parse a null string.
'       Cannot parse ''.
'       'True' --> True
'       'False' --> False
'       'true' --> True
'       'false' --> False
'       '    true    ' --> True
'       'TrUe' --> True
'       'fAlSe' --> False
'       Cannot parse 'fa lse'.
'       Cannot parse '0'.
'       Cannot parse '1'.
'       Cannot parse '-1'.
'       Cannot parse 'string'.
'       
'       Unable to parse ''
'       Unable to parse ''
'       'True' --> True
'       'False' --> False
'       'true' --> True
'       'false' --> False
'       '    true    ' --> True
'       'TrUe' --> True
'       'fAlSe' --> False
'       Cannot parse 'fa lse'.
'       Unable to parse '0'
'       Unable to parse '1'
'       Unable to parse '-1'
'       Unable to parse 'string'

Se si esegue la programmazione in Visual Basic, è possibile usare la funzione per convertire la CBool rappresentazione stringa di un numero in un valore booleano. "0" viene convertito in falsee la rappresentazione stringa di qualsiasi valore non zero viene convertita in true. Se non si esegue la programmazione in Visual Basic, è necessario convertire la stringa numerica in un numero prima di convertirla in un valore booleano. Nell'esempio seguente viene illustrata la conversione di una matrice di numeri interi in valori booleani.

using System;

public class Example
{
   public static void Main()
   {
      String[] values = { "09", "12.6", "0", "-13 " };
      foreach (var value in values) {
         bool success, result;
         int number;
         success = Int32.TryParse(value, out number);
         if (success) {
            // The method throws no exceptions.
            result = Convert.ToBoolean(number);
            Console.WriteLine("Converted '{0}' to {1}", value, result);
         }
         else {
            Console.WriteLine("Unable to convert '{0}'", value);
         }
      }
   }
}
// The example displays the following output:
//       Converted '09' to True
//       Unable to convert '12.6'
//       Converted '0' to False
//       Converted '-13 ' to True
open System

let values = [ "09"; "12.6"; "0"; "-13 " ]
for value in values do
    match Int32.TryParse value with
    | true, number -> 
        // The method throws no exceptions.
        let result = Convert.ToBoolean number
        printfn $"Converted '{value}' to {result}"
    | false, _ ->
        printfn $"Unable to convert '{value}'"

// The example displays the following output:
//       Converted '09' to True
//       Unable to convert '12.6'
//       Converted '0' to False
//       Converted '-13 ' to True
Module Example
   Public Sub Main()
      Dim values() As String = { "09", "12.6", "0", "-13 " }
      For Each value In values
         Dim success, result As Boolean
         Dim number As Integer 
         success = Int32.TryParse(value, number)
         If success Then
            ' The method throws no exceptions.
            result = Convert.ToBoolean(number)
            Console.WriteLine("Converted '{0}' to {1}", value, result)
         Else
            Console.WriteLine("Unable to convert '{0}'", value)
         End If         
      Next
   End Sub
End Module
' The example displays the following output:
'       Converted '09' to True
'       Unable to convert '12.6'
'       Converted '0' to False
'       Converted '-13 ' to True

Confrontare i valori booleani

Poiché i valori booleani sono o false, è necessario chiamare in modo esplicito il metodo, che indica se un'istanza CompareTo è true maggiore, minore o uguale a un valore specificato. In genere, per confrontare due variabili booleane, si chiama il metodo o si usa l'operatore Equals di uguaglianza della lingua.

Tuttavia, quando si vuole confrontare una variabile booleana con il valore booleano letterale o false, non è necessario eseguire un confronto esplicito, perché il risultato della valutazione di un valore booleano è il valore true booleano. Ad esempio, le espressioni

if (booleanValue == true) {
if booleanValue = true then
If booleanValue = True Then

e

if (booleanValue) {
if booleanValue then
If booleanValue Then

sono equivalenti, ma il secondo è più compatto. Tuttavia, entrambe le tecniche offrono prestazioni paragonabili.

Usare i booleani come valori binari

Un valore booleano occupa un byte di memoria, come illustrato nell'esempio C# o F# seguente. L'esempio C# deve essere compilato con l'opzione /unsafe .

using System;

public struct BoolStruct
{
   public bool flag1;
   public bool flag2;
   public bool flag3;
   public bool flag4;
   public bool flag5;
}

public class Example
{
   public static void Main()
   {
      unsafe {
         BoolStruct b = new BoolStruct();
         bool* addr = (bool*) &b;
         Console.WriteLine("Size of BoolStruct: {0}", sizeof(BoolStruct));
         Console.WriteLine("Field offsets:");
         Console.WriteLine("   flag1: {0}", (bool*) &b.flag1 - addr);
         Console.WriteLine("   flag1: {0}", (bool*) &b.flag2 - addr);
         Console.WriteLine("   flag1: {0}", (bool*) &b.flag3 - addr);
         Console.WriteLine("   flag1: {0}", (bool*) &b.flag4 - addr);
         Console.WriteLine("   flag1: {0}", (bool*) &b.flag5 - addr);
      }
   }
}
// The example displays the following output:
//       Size of BoolStruct: 5
//       Field offsets:
//          flag1: 0
//          flag1: 1
//          flag1: 2
//          flag1: 3
//          flag1: 4
#nowarn "9" "51"
open FSharp.NativeInterop

[<Struct>]
type BoolStruct =
   val flag1: bool
   val flag2: bool
   val flag3: bool
   val flag4: bool
   val flag5: bool

let inline nint addr = NativePtr.toNativeInt addr

let mutable b = BoolStruct()
let addr = &&b

printfn $"Size of BoolStruct: {sizeof<BoolStruct>}"
printfn "Field offsets:"
printfn $"   flag1: {nint &&b.flag1 - nint addr}"
printfn $"   flag2: {nint &&b.flag2 - nint addr}"
printfn $"   flag3: {nint &&b.flag3 - nint addr}"
printfn $"   flag4: {nint &&b.flag4 - nint addr}"
printfn $"   flag5: {nint &&b.flag5 - nint addr}"

// The example displays the following output:
//       Size of BoolStruct: 5
//       Field offsets:
//          flag1: 0
//          flag1: 1
//          flag1: 2
//          flag1: 3
//          flag1: 4

Il bit a basso ordine di byte viene usato per rappresentare il relativo valore. Un valore pari a 1 rappresenta ; un valore pari a 0 rappresenta truefalse.

Suggerimento

È possibile usare la System.Collections.Specialized.BitVector32 struttura per usare i set di valori booleani.

È possibile convertire un valore booleano nella relativa rappresentazione binaria chiamando il BitConverter.GetBytes(Boolean) metodo . Il metodo restituisce una matrice di byte con un singolo elemento. Per ripristinare un valore booleano dalla relativa rappresentazione binaria, è possibile chiamare il BitConverter.ToBoolean(Byte[], Int32) metodo .

Nell'esempio seguente viene chiamato il BitConverter.GetBytes metodo per convertire un valore booleano nella relativa rappresentazione binaria e vengono visualizzati i singoli bit del valore e quindi chiama il metodo per ripristinare il BitConverter.ToBoolean valore dalla relativa rappresentazione binaria.

using System;

public class Example
{
   public static void Main()
   {
      bool[] flags = { true, false };
      foreach (var flag in flags) {
         // Get binary representation of flag.
         Byte value = BitConverter.GetBytes(flag)[0];
         Console.WriteLine("Original value: {0}", flag);
         Console.WriteLine("Binary value:   {0} ({1})", value,
                           GetBinaryString(value));
         // Restore the flag from its binary representation.
         bool newFlag = BitConverter.ToBoolean( new Byte[] { value }, 0);
         Console.WriteLine("Restored value: {0}\n", flag);
      }
   }

   private static string GetBinaryString(Byte value)
   {
      string retVal = Convert.ToString(value, 2);
      return new string('0', 8 - retVal.Length) + retVal;
   }
}
// The example displays the following output:
//       Original value: True
//       Binary value:   1 (00000001)
//       Restored value: True
//
//       Original value: False
//       Binary value:   0 (00000000)
//       Restored value: False
open System

let getBinaryString (value: byte) =
   let retValue = Convert.ToString(value, 2)
   String('0', 8 - retValue.Length) + retValue

let flags = [ true; false ]
for flag in flags do
      // Get binary representation of flag.
      let value = BitConverter.GetBytes(flag)[0];
      printfn $"Original value: {flag}"
      printfn $"Binary value:   {value} ({getBinaryString value})"
      // Restore the flag from its binary representation.
      let newFlag = BitConverter.ToBoolean([|value|], 0)
      printfn $"Restored value: {newFlag}\n"

// The example displays the following output:
//       Original value: True
//       Binary value:   1 (00000001)
//       Restored value: True
//
//       Original value: False
//       Binary value:   0 (00000000)
//       Restored value: False
Module Example
   Public Sub Main()
      Dim flags() As Boolean = { True, False }
      For Each flag In flags
         ' Get binary representation of flag.
         Dim value As Byte = BitConverter.GetBytes(flag)(0)
         Console.WriteLine("Original value: {0}", flag)
         Console.WriteLine("Binary value:   {0} ({1})", value, 
                           GetBinaryString(value))
         ' Restore the flag from its binary representation.
         Dim newFlag As Boolean = BitConverter.ToBoolean( { value }, 0)
         Console.WriteLine("Restored value: {0}", flag)
         Console.WriteLine()
      Next
   End Sub
   
   Private Function GetBinaryString(value As Byte) As String
      Dim retVal As String = Convert.ToString(value, 2)
      Return New String("0"c, 8 - retVal.Length) + retVal
   End Function
End Module
' The example displays the following output:
'       Original value: True
'       Binary value:   1 (00000001)
'       Restored value: True
'       
'       Original value: False
'       Binary value:   0 (00000000)
'       Restored value: False

Eseguire operazioni con valori booleani

Questa sezione illustra come vengono usati i valori booleani nelle app. La prima sezione illustra l'uso come flag. Il secondo illustra l'uso per operazioni aritmetiche.

Valori booleani come flag

Le variabili booleane sono più comunemente usate come flag, per segnalare la presenza o l'assenza di alcune condizioni. Ad esempio, nel String.Compare(String, String, Boolean) metodo, il parametro finale, ignoreCaseè un flag che indica se il confronto di due stringhe è senza distinzione tra maiuscole e minuscole ( è ) o la distinzione tra maiuscole e minuscole (ignoreCaseignoreCase è truefalse). Il valore del flag può quindi essere valutato in un'istruzione condizionale.

Nell'esempio seguente viene usata una semplice app console per illustrare l'uso delle variabili booleane come flag. L'app accetta i parametri della riga di comando che consentono il reindirizzamento dell'output a un file specificato (l'opzione) e che consentono l'invio dell'output a un file specificato e alla console ( /f l'opzione /b ). L'app definisce un flag denominato isRedirected per indicare se l'output deve essere inviato a un file e un flag denominato isBoth per indicare che l'output deve essere inviato alla console. Si noti che l'esempio F# usa una funzione ricorsiva per analizzare gli argomenti.

using System;
using System.IO;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Initialize flag variables.
      bool isRedirected = false;
      bool isBoth = false;
      String fileName = "";
      StreamWriter sw = null;

      // Get any command line arguments.
      String[] args = Environment.GetCommandLineArgs();
      // Handle any arguments.
      if (args.Length > 1) {
         for (int ctr = 1; ctr < args.Length; ctr++) {
            String arg = args[ctr];
            if (arg.StartsWith("/") || arg.StartsWith("-")) {
               switch (arg.Substring(1).ToLower())
               {
                  case "f":
                     isRedirected = true;
                     if (args.Length < ctr + 2) {
                        ShowSyntax("The /f switch must be followed by a filename.");
                        return;
                     }
                     fileName = args[ctr + 1];
                     ctr++;
                     break;
                  case "b":
                     isBoth = true;
                     break;
                  default:
                     ShowSyntax(String.Format("The {0} switch is not supported",
                                              args[ctr]));
                     return;
               }
            }
         }
      }

      // If isBoth is True, isRedirected must be True.
      if (isBoth &&  ! isRedirected) {
         ShowSyntax("The /f switch must be used if /b is used.");
         return;
      }

      // Handle output.
      if (isRedirected) {
         sw = new StreamWriter(fileName);
         if (!isBoth)
            Console.SetOut(sw);
      }
      String msg = String.Format("Application began at {0}", DateTime.Now);
      Console.WriteLine(msg);
      if (isBoth) sw.WriteLine(msg);
      Thread.Sleep(5000);
      msg = String.Format("Application ended normally at {0}", DateTime.Now);
      Console.WriteLine(msg);
      if (isBoth) sw.WriteLine(msg);
      if (isRedirected) sw.Close();
   }

   private static void ShowSyntax(String errMsg)
   {
      Console.WriteLine(errMsg);
      Console.WriteLine("\nSyntax: Example [[/f <filename> [/b]]\n");
   }
}
open System
open System.IO
open System.Threading

let showSyntax errMsg =
    printfn $"{errMsg}\n\nSyntax: Example [[/f <filename> [/b]]\n" 

let mutable isRedirected = false
let mutable isBoth = false
let mutable fileName = ""

let rec parse = function
    | [] -> ()
    | "-b" :: rest
    | "/b" :: rest ->
        isBoth <- true
        // Parse remaining arguments.
        parse rest
    | "-f" :: file :: rest
    | "/f" :: file :: rest ->
        isRedirected <- true
        fileName <- file
        // Parse remaining arguments.
        parse rest
    | "-f" :: []
    | "/f" :: [] ->
        isRedirected <- true
        // No more arguments to parse.
    | x -> showSyntax $"The {x} switch is not supported"

Environment.GetCommandLineArgs()[1..]
|> List.ofArray
|> parse

// If isBoth is True, isRedirected must be True.
if isBoth && not isRedirected then
    showSyntax "The /f switch must be used if /b is used."
// If isRedirected is True, a fileName must be specified.
elif fileName = "" && isRedirected then
    showSyntax "The /f switch must be followed by a filename."    
else
    use mutable sw = null

    // Handle output.
    let writeLine =
        if isRedirected then 
            sw <- new StreamWriter(fileName)
            if isBoth then
                fun text -> 
                    printfn "%s" text
                    sw.WriteLine text
            else sw.WriteLine
        else printfn "%s"

    writeLine $"Application began at {DateTime.Now}"
    Thread.Sleep 5000
    writeLine $"Application ended normally at {DateTime.Now}"
Imports System.IO
Imports System.Threading

Module Example
   Public Sub Main()
      ' Initialize flag variables.
      Dim isRedirected, isBoth As Boolean 
      Dim fileName As String = ""
      Dim sw As StreamWriter = Nothing
      
      ' Get any command line arguments.
      Dim args() As String = Environment.GetCommandLineArgs()
      ' Handle any arguments.
      If args.Length > 1 Then
         For ctr = 1 To args.Length - 1
            Dim arg As String = args(ctr)
            If arg.StartsWith("/") OrElse arg.StartsWith("-") Then
               Select Case arg.Substring(1).ToLower()
                  Case "f"
                     isRedirected = True
                     If args.Length < ctr + 2 Then
                        ShowSyntax("The /f switch must be followed by a filename.")
                        Exit Sub
                     End If
                     fileName = args(ctr + 1)
                     ctr += 1
                  Case "b"
                     isBoth = True
                  Case Else
                     ShowSyntax(String.Format("The {0} switch is not supported", 
                                              args(ctr)))
                     Exit Sub
               End Select
            End If   
         Next
      End If

      ' If isBoth is True, isRedirected must be True.
      If isBoth And Not isRedirected Then 
         ShowSyntax("The /f switch must be used if /b is used.")
         Exit Sub
      End If

      ' Handle output.
      If isRedirected Then
         sw = New StreamWriter(fileName) 
         If Not IsBoth Then
            Console.SetOut(sw) 
         End If
      End If     
      Dim msg As String = String.Format("Application began at {0}", Date.Now)
      Console.WriteLine(msg)
      If isBoth Then sw.WriteLine(msg)
      Thread.Sleep(5000)
      msg = String.Format("Application ended normally at {0}", Date.Now)
      Console.WriteLine(msg)
      If isBoth Then sw.WriteLine(msg)
      If isRedirected Then sw.Close()
   End Sub
   
   Private Sub ShowSyntax(errMsg As String)
      Console.WriteLine(errMsg)
      Console.WriteLine()
      Console.WriteLine("Syntax: Example [[/f <filename> [/b]]")
      Console.WriteLine()
   End Sub
End Module

Operazioni booleane e aritmetice

Un valore booleano viene talvolta usato per indicare la presenza di una condizione che attiva un calcolo matematico. Ad esempio, una hasShippingCharge variabile può fungere da flag per indicare se aggiungere addebiti di spedizione a un importo della fattura.

Poiché un'operazione con un valore non ha alcun effetto sul risultato di un'operazione false , non è necessario convertire il booleano in un valore integrale da utilizzare nell'operazione matematica. È invece possibile usare la logica condizionale.

Nell'esempio seguente viene calcolato un importo costituito da un subtotale, un addebito di spedizione e un addebito facoltativo del servizio. La hasServiceCharge variabile determina se viene applicato l'addebito del servizio. Anziché convertire hasServiceCharge in un valore numerico e moltiplicarlo in base all'importo dell'addebito del servizio, nell'esempio viene usata la logica condizionale per aggiungere l'importo dell'addebito del servizio se applicabile.

using System;

public class Example
{
   public static void Main()
   {
      bool[] hasServiceCharges = { true, false };
      Decimal subtotal = 120.62m;
      Decimal shippingCharge = 2.50m;
      Decimal serviceCharge = 5.00m;

      foreach (var hasServiceCharge in hasServiceCharges) {
         Decimal total = subtotal + shippingCharge +
                                (hasServiceCharge ? serviceCharge : 0);
         Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.",
                           total, hasServiceCharge);
      }
   }
}
// The example displays output like the following:
//       hasServiceCharge = True: The total is $128.12.
//       hasServiceCharge = False: The total is $123.12.
let hasServiceCharges = [ true; false ]
let subtotal = 120.62M
let shippingCharge = 2.50M
let serviceCharge = 5.00M

for hasServiceCharge in hasServiceCharges do
    let total = 
        subtotal + shippingCharge + if hasServiceCharge then serviceCharge else 0M
    printfn $"hasServiceCharge = {hasServiceCharge}: The total is {total:C2}."

// The example displays output like the following:
//       hasServiceCharge = True: The total is $128.12.
//       hasServiceCharge = False: The total is $123.12.
Module Example
   Public Sub Main()
      Dim hasServiceCharges() As Boolean = { True, False }
      Dim subtotal As Decimal = 120.62d
      Dim shippingCharge As Decimal = 2.50d
      Dim serviceCharge As Decimal = 5.00d
      
      For Each hasServiceCharge In hasServiceCharges
         Dim total As Decimal = subtotal + shippingCharge + 
                                If(hasServiceCharge, serviceCharge, 0)
         Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.", 
                           total, hasServiceCharge)                       
      Next
   End Sub
End Module
' The example displays output like the following:
'       hasServiceCharge = True: The total is $128.12.
'       hasServiceCharge = False: The total is $123.12.

Booleans e interoperabilità

Anche se il marshalling dei tipi di dati di base a COM è in genere semplice, il Boolean tipo di dati è un'eccezione. È possibile applicare l'attributo al marshalling del MarshalAsAttributeBoolean tipo a una delle rappresentazioni seguenti:

Tipo di enumerazione Formato non gestito
UnmanagedType.Bool Valore intero a 4 byte, dove qualsiasi valore diverso da zero rappresenta true e 0 rappresenta false. Si tratta del formato predefinito di un campo in una struttura e di un BooleanBoolean parametro nelle chiamate di chiamata della piattaforma.
UnmanagedType.U1 Valore intero a 1 byte, dove il valore 1 rappresenta true e 0 rappresenta false.
UnmanagedType.VariantBool Valore intero a 2 byte, dove -1 rappresenta true e 0 rappresenta false. Si tratta del formato predefinito di un Boolean parametro nelle chiamate di interoperabilità COM.

Campi

FalseString

Rappresenta un valore booleano false sotto forma di stringa. Questo campo è di sola lettura.

TrueString

Rappresenta un valore booleano true sotto forma di stringa. Questo campo è di sola lettura.

Metodi

CompareTo(Boolean)

Confronta questa istanza con un oggetto Boolean specificato e restituisce un intero che indica la relazione reciproca.

CompareTo(Object)

Confronta l'istanza con un oggetto specificato e restituisce un valore intero che indica la relazione reciproca.

Equals(Boolean)

Restituisce un valore che indica se questa istanza è uguale a un oggetto Boolean specificato.

Equals(Object)

Restituisce un valore che indica se questa istanza è uguale a un oggetto specificato.

GetHashCode()

Restituisce il codice hash per l'istanza.

GetTypeCode()

Restituisce il codice del tipo per il tipo di valore Boolean.

Parse(ReadOnlySpan<Char>)

Converte la rappresentazione in forma di intervallo specificata di un valore logico nell'oggetto Boolean equivalente.

Parse(String)

Converte la rappresentazione di stringa specificata di un valore logico nel relativo valore Boolean equivalente.

ToString()

Converte il valore dell'istanza corrente nella rappresentazione di stringa equivalente ("True" o "False").

ToString(IFormatProvider)

Converte il valore dell'istanza corrente nella rappresentazione di stringa equivalente ("True" o "False").

TryFormat(Span<Char>, Int32)

Tenta di formattare il valore dell'istanza booleana corrente nell'intervallo di caratteri specificato.

TryParse(ReadOnlySpan<Char>, Boolean)

Tenta di convertire la rappresentazione in forma di intervallo specificata di un valore logico nell'oggetto Boolean equivalente.

TryParse(String, Boolean)

Prova a convertire la rappresentazione di stringa specificata di un valore logico nell'oggetto Boolean equivalente.

Implementazioni dell'interfaccia esplicita

IComparable.CompareTo(Object)

Confronta l'istanza corrente con un altro oggetto dello stesso tipo e restituisce un intero che indica se l'istanza corrente precede, segue o si trova nella stessa posizione dell'altro oggetto all'interno dell'ordinamento.

IConvertible.GetTypeCode()

Restituisce l'oggetto TypeCode per questa istanza.

IConvertible.ToBoolean(IFormatProvider)

Per una descrizione di questo membro, vedere ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider)

Per una descrizione di questo membro, vedere ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider)

Questa conversione non è supportata. Il tentativo di usare questo metodo genera un'eccezione InvalidCastException.

IConvertible.ToDateTime(IFormatProvider)

Questa conversione non è supportata. Il tentativo di usare questo metodo genera un'eccezione InvalidCastException.

IConvertible.ToDecimal(IFormatProvider)

Per una descrizione di questo membro, vedere ToDecimal(IFormatProvider).

IConvertible.ToDouble(IFormatProvider)

Per una descrizione di questo membro, vedere ToDouble(IFormatProvider).

IConvertible.ToInt16(IFormatProvider)

Per una descrizione di questo membro, vedere ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider)

Per una descrizione di questo membro, vedere ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider)

Per una descrizione di questo membro, vedere ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider)

Per una descrizione di questo membro, vedere ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider)

Per una descrizione di questo membro, vedere ToSingle(IFormatProvider).

IConvertible.ToString(IFormatProvider)

Converte il valore di questa istanza in una stringa equivalente usando le informazioni di formattazione specifiche delle impostazioni cultura.

IConvertible.ToType(Type, IFormatProvider)

Per una descrizione di questo membro, vedere ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider)

Per una descrizione di questo membro, vedere ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider)

Per una descrizione di questo membro, vedere ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider)

Per una descrizione di questo membro, vedere ToUInt64(IFormatProvider).

IParsable<Boolean>.Parse(String, IFormatProvider)

Analizza una stringa in un valore.

IParsable<Boolean>.TryParse(String, IFormatProvider, Boolean)

Rappresenta un valore booleano (true o false).

ISpanParsable<Boolean>.Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizza un intervallo di caratteri in un valore.

ISpanParsable<Boolean>.TryParse(ReadOnlySpan<Char>, IFormatProvider, Boolean)

Rappresenta un valore booleano (true o false).

Si applica a

Thread safety

Tutti i membri di questo tipo sono thread safe. I membri che sembrano modificare lo stato dell'istanza restituiscono effettivamente una nuova istanza inizializzata con il nuovo valore. Come per qualsiasi altro tipo, la lettura e la scrittura in una variabile condivisa che contiene un'istanza di questo tipo deve essere protetta da un blocco per garantire la sicurezza del thread.