Estructura System.Boolean

En este artículo se proporcionan comentarios adicionales a la documentación de referencia de esta API.

Una Boolean instancia puede tener dos valores: true o false.

La Boolean estructura proporciona métodos que admiten las siguientes tareas:

En este artículo se explican estas tareas y otros detalles de uso.

Formato de valores booleanos

La representación de cadena de es Boolean "True" para un true valor o "False" para un false valor. La representación de cadena de un Boolean valor se define mediante los campos y FalseString de solo TrueString lectura.

Use el ToString método para convertir valores booleanos en cadenas. La estructura booleana incluye dos ToString sobrecargas: el método sin ToString() parámetros y el método , que incluye un parámetro que controla el ToString(IFormatProvider) formato. Sin embargo, dado que este parámetro se omite, las dos sobrecargas producen cadenas idénticas. El ToString(IFormatProvider) método no admite el formato que distingue la referencia cultural.

En el ejemplo siguiente se muestra el formato con el ToString método . Tenga en cuenta que los ejemplos de C# y VB usan la característica de formato compuesto, mientras que el ejemplo de F# usa la interpolación de cadenas. En ambos casos, se llama implícitamente al ToString método .

using System;

public class Example10
{
   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 Example9
    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

Dado que la Boolean estructura solo puede tener dos valores, es fácil agregar formato personalizado. Para un formato personalizado sencillo en el que se sustituyen otros literales de cadena por "True" y "False", puede usar cualquier característica de evaluación condicional compatible con el lenguaje, como el operador condicional en C# o el operador If de Visual Basic. En el ejemplo siguiente se usa esta técnica para dar formato Boolean a los valores como "Sí" y "No", en lugar de "True" y "False".

using System;

public class Example11
{
    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

Para operaciones de formato personalizado más complejas, incluido el formato que distingue la referencia cultural, puede llamar al String.Format(IFormatProvider, String, Object[]) método y proporcionar una ICustomFormatter implementación. En el ejemplo siguiente se implementan las ICustomFormatter interfaces e IFormatProvider para proporcionar cadenas booleanas sensibles a la referencia cultural para las referencias culturales inglés (Estados Unidos), francés (Francia) y ruso (Rusia).

using System;
using System.Globalization;

public class Example4
{
   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 Example4
    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': верно

Opcionalmente, puede usar archivos de recursos para definir cadenas booleanas específicas de la referencia cultural.

Conversión a y desde valores booleanos

La Boolean estructura implementa la IConvertible interfaz . Como resultado, puede usar la Convert clase para realizar conversiones entre un Boolean valor y cualquier otro tipo primitivo en .NET, o bien puede llamar a las implementaciones explícitas de la Boolean estructura. Sin embargo, no se admiten conversiones entre y Boolean los siguientes tipos, por lo que los métodos de conversión correspondientes producen una InvalidCastException excepción:

Todas las conversiones de números enteros o de punto flotante a valores booleanos convierten valores distintos de cero en true y cero en false. En el ejemplo siguiente se muestra esto llamando a sobrecargas seleccionadas de la Convert.ToBoolean clase .

using System;

public class Example2
{
   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 Example2
    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 = 0.0001
        Console.WriteLine(Convert.ToBoolean(sngValue))
    End Sub
End Module
' The example displays the following output:
'       True
'       False
'       True
'       True
'       True
'       False
'       True

Al convertir de booleano a valores numéricos, los métodos de conversión de la Convert clase convierten true en 1 y false en 0. Sin embargo, las funciones de conversión de Visual Basic convierten true a 255 (para conversiones a Byte valores) o -1 (para todas las demás conversiones numéricas). En el ejemplo siguiente se convierten en valores numéricos true mediante un Convert método y, en el caso del ejemplo de Visual Basic, mediante el operador de conversión propio del lenguaje Visual Basic.

using System;

public class Example3
{
   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 Example3
    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)

Para las conversiones de Boolean a valores de cadena, consulte la sección Formato de valores booleanos. Para ver las conversiones de cadenas a Boolean valores, consulte la sección Análisis de valores booleanos.

Análisis de valores booleanos

La Boolean estructura incluye dos métodos de análisis estáticos y TryParseParse , que convierten una cadena en un valor booleano. La representación de cadena de un valor booleano se define mediante los equivalentes que no distinguen mayúsculas de minúsculas de los valores de los TrueString campos y FalseString , que son "True" y "False", respectivamente. En otras palabras, las únicas cadenas que analizan correctamente son "True", "False", "true", "false" o algún equivalente de mayúsculas y minúsculas mixtas. No se pueden analizar correctamente cadenas numéricas como "0" o "1". Los caracteres de espacio en blanco iniciales o finales no se tienen en cuenta al realizar la comparación de cadenas.

En el ejemplo siguiente se usan los Parse métodos y TryParse para analizar una serie de cadenas. Tenga en cuenta que solo se pueden analizar correctamente los equivalentes que no distinguen mayúsculas de minúsculas de "True" y "False".

using System;

public class Example7
{
   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 Example7
    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) Then
                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'

Si está programando en Visual Basic, puede usar la CBool función para convertir la representación de cadena de un número en un valor booleano. "0" se convierte en falsey la representación de cadena de cualquier valor distinto de cero se convierte en true. Si no está programando en Visual Basic, debe convertir la cadena numérica en un número antes de convertirla en un valor booleano. En el ejemplo siguiente se muestra esto convirtiendo una matriz de enteros en valores booleanos.

using System;

public class Example8
{
   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 Example8
    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

Comparación de valores booleanos

Dado que los valores booleanos son true o false, hay poca razón para llamar explícitamente al CompareTo método , lo que indica si una instancia es mayor que, menor o igual que un valor especificado. Normalmente, para comparar dos variables booleanas, se llama al método o se usa el Equals operador de igualdad del lenguaje.

Sin embargo, cuando desea comparar una variable booleana con el valor true booleano literal o false, no es necesario realizar una comparación explícita, ya que el resultado de evaluar un valor booleano es ese valor booleano. Por ejemplo, las dos expresiones siguientes son equivalentes, pero la segunda es más compacta. Sin embargo, ambas técnicas ofrecen un rendimiento comparable.

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

Trabajar con valores booleanos como valores binarios

Un valor booleano ocupa un byte de memoria, como se muestra en el ejemplo siguiente. El ejemplo de C# debe compilarse con el /unsafe modificador .

using System;

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

public class Example9
{
   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

El bit de orden bajo del byte se usa para representar su valor. Un valor de 1 representa true; un valor de 0 representa false.

Sugerencia

Puede usar la System.Collections.Specialized.BitVector32 estructura para trabajar con conjuntos de valores booleanos.

Puede convertir un valor booleano en su representación binaria llamando al BitConverter.GetBytes(Boolean) método . El método devuelve una matriz de bytes con un único elemento. Para restaurar un valor booleano a partir de su representación binaria, puede llamar al BitConverter.ToBoolean(Byte[], Int32) método .

En el ejemplo siguiente se llama al BitConverter.GetBytes método para convertir un valor booleano en su representación binaria y se muestran los bits individuales del valor y, a continuación, se llama al BitConverter.ToBoolean método para restaurar el valor a partir de su representación binaria.

using System;

public class Example1
{
    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 Example1
    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

Realización de operaciones con valores booleanos

En esta sección se muestra cómo se usan los valores booleanos en las aplicaciones. En la primera sección se describe su uso como marca. En el segundo se muestra su uso para las operaciones aritméticas.

Valores booleanos como marcas

Las variables booleanas se usan normalmente como marcas para indicar la presencia o ausencia de alguna condición. Por ejemplo, en el String.Compare(String, String, Boolean) método , el parámetro final, ignoreCase, es una marca que indica si la comparación de dos cadenas no distingue mayúsculas de minúsculas (ignoreCase es true) o distingue mayúsculas de minúsculas (ignoreCase es false). A continuación, el valor de la marca se puede evaluar en una instrucción condicional.

En el ejemplo siguiente se usa una aplicación de consola sencilla para ilustrar el uso de variables booleanas como marcas. La aplicación acepta parámetros de línea de comandos que permiten redirigir la salida a un archivo especificado (el /f modificador) y que permiten enviar la salida a un archivo especificado y a la consola (el /b modificador). La aplicación define una marca denominada isRedirected para indicar si la salida se va a enviar a un archivo y una marca denominada isBoth para indicar que la salida se debe enviar a la consola. En el ejemplo de F# se usa una función recursiva para analizar los argumentos.

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

public class Example5
{
   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 Example5
    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

Booleans y operaciones aritméticas

A veces se usa un valor booleano para indicar la presencia de una condición que desencadena un cálculo matemático. Por ejemplo, una hasShippingCharge variable podría servir como marca para indicar si se agregan cargos de envío a un importe de factura.

Dado que una operación con un false valor no tiene ningún efecto en el resultado de una operación, no es necesario convertir el valor booleano en un valor entero que se usará en la operación matemática. En su lugar, puede usar la lógica condicional.

En el ejemplo siguiente se calcula una cantidad que consta de un subtotal, un cargo de envío y un cargo de servicio opcional. La hasServiceCharge variable determina si se aplica el cargo de servicio. En lugar de convertir hasServiceCharge en un valor numérico y multiplicarlo por la cantidad del cargo de servicio, en el ejemplo se usa lógica condicional para agregar el importe del cargo de servicio si es aplicable.

using System;

public class Example6
{
   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 Example6
    Public Sub Main()
        Dim hasServiceCharges() As Boolean = {True, False}
        Dim subtotal As Decimal = 120.62D
        Dim shippingCharge As Decimal = 2.5D
        Dim serviceCharge As Decimal = 5D

        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 interoperabilidad

Aunque la serialización de tipos de datos base en COM suele ser sencilla, el Boolean tipo de datos es una excepción. Puede aplicar el MarshalAsAttribute atributo para serializar el Boolean tipo a cualquiera de las siguientes representaciones:

Tipo de enumeración Formato no administrado
UnmanagedType.Bool Valor entero de 4 bytes, donde cualquier valor distinto de cero representa true y 0 representa false. Este es el formato predeterminado de un Boolean campo en una estructura y de un Boolean parámetro en las llamadas de invocación de plataforma.
UnmanagedType.U1 Valor entero de 1 byte, donde el 1 representa true y 0 representa false.
UnmanagedType.VariantBool Valor entero de 2 bytes, donde -1 representa true y 0 representa false. Este es el formato predeterminado de un Boolean parámetro en las llamadas de interoperabilidad COM.