Boolean Estrutura
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Representa um valor booliano (true
ou 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)
- Herança
- Atributos
- Implementações
Comentários
Uma Boolean instância pode ter um dos dois valores: true
ou false
.
A Boolean estrutura fornece métodos que dão suporte às seguintes tarefas:
Convertendo valores boolianos em cadeias de caracteres: ToString
Analisando cadeias de caracteres para convertê-las em valores boolianos: Parse e TryParse
As seções a seguir explicam essas tarefas e outros detalhes de uso:
- Formatar valores boolianos
- Converter de e para valores boolianos
- Analisar valores boolianos
- Comparar valores boolianos
- Trabalhar com boolianos como valores binários
- Executar operações com valores boolianos
- Boolianos e Interoperabilidade
Formatar valores boolianos
A representação de cadeia de caracteres de um Boolean é "True" para um true
valor ou "False" para um false
valor. A representação de cadeia de caracteres de um Boolean valor é definida pelos campos somente TrueString leitura e FalseString .
Use o ToString método para converter valores boolianos em cadeias de caracteres. A estrutura booliana inclui duas ToString sobrecargas: o método sem ToString() parâmetros e o ToString(IFormatProvider) método , que inclui um parâmetro que controla a formatação. No entanto, como esse parâmetro é ignorado, as duas sobrecargas produzem cadeias de caracteres idênticas. O ToString(IFormatProvider) método não dá suporte à formatação sensível à cultura.
O exemplo a seguir ilustra a formatação com o ToString método . Observe que os exemplos de C# e VB usam o recurso de formatação composta , enquanto o exemplo F# usa interpolação de cadeia de caracteres. Em ambos os casos, o ToString método é chamado implicitamente.
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
Como a Boolean estrutura pode ter apenas dois valores, é fácil adicionar formatação personalizada. Para formatação personalizada simples na qual outros literais de cadeia de caracteres são substituídos por "True" e "False", você pode usar qualquer recurso de avaliação condicional compatível com seu idioma, como o operador condicional em C# ou o operador If no Visual Basic. O exemplo a seguir usa essa técnica para formatar Boolean valores como "Sim" e "Não" em vez de "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
Para operações de formatação personalizadas mais complexas, incluindo formatação sensível à cultura, você pode chamar o String.Format(IFormatProvider, String, Object[]) método e fornecer uma implementação ICustomFormatter . O exemplo a seguir implementa as ICustomFormatter interfaces e IFormatProvider para fornecer cadeias de caracteres boolianas sensíveis à cultura para as culturas inglesa (Estados Unidos), francesa (França) e russa (Rússia).
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': верно
Opcionalmente, você pode usar arquivos de recursos para definir cadeias de caracteres boolianas específicas da cultura.
Converter de e para valores boolianos
A Boolean estrutura implementa a IConvertible interface . Como resultado, você pode usar a Convert classe para executar conversões entre um Boolean valor e qualquer outro tipo primitivo no .NET ou pode chamar as Boolean implementações explícitas da estrutura. No entanto, não há suporte para conversões entre um Boolean e os seguintes tipos, portanto, os métodos de conversão correspondentes geram uma exceção InvalidCastException :
Conversão entre Boolean e (os Convert.ToBoolean(Char) métodos e Convert.ToChar(Boolean)Char )
Conversão entre Boolean e (os Convert.ToBoolean(DateTime) métodos e Convert.ToDateTime(Boolean)DateTime )
Todas as conversões de números integrais ou de ponto flutuante em valores boolianos convertem valores não zero em true
e valores zero em false
. O exemplo a seguir ilustra isso chamando sobrecargas selecionadas da 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
Ao converter de valores boolianos em numéricos, os métodos de conversão da Convert classe convertem true
em 1 e false
em 0. No entanto, as funções de conversão do Visual Basic são convertidas true
em 255 (para conversões em Byte valores) ou -1 (para todas as outras conversões numéricas). O exemplo a seguir converte true
em valores numéricos usando um Convert método e, no caso do exemplo do Visual Basic, usando o operador de conversão da própria linguagem do 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)
Para conversões de em valores de Boolean cadeia de caracteres, consulte a seção Formatação de valores boolianos . Para conversões de cadeias de caracteres em Boolean valores, consulte a seção Analisando valores boolianos .
Analisar valores boolianos
A Boolean estrutura inclui dois métodos de análise estáticos, Parse e TryParse, que convertem uma cadeia de caracteres em um valor booliano. A representação de cadeia de caracteres de um valor booliano é definida pelos equivalentes que não diferenciam maiúsculas de minúsculas dos valores dos TrueString campos e FalseString , que são "True" e "False", respectivamente. Em outras palavras, as únicas cadeias de caracteres que analisam com êxito são "True", "False", "true", "false" ou algum equivalente de maiúsculas e minúsculas mistas. Não é possível analisar com êxito cadeias de caracteres numéricas, como "0" ou "1". Caracteres de espaço em branco à esquerda ou à direita não são considerados ao executar a comparação de cadeia de caracteres.
O exemplo a seguir usa os Parse métodos e TryParse para analisar várias cadeias de caracteres. Observe que somente os equivalentes que não diferenciam maiúsculas de minúsculas de "True" e "False" podem ser analisados com êxito.
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 você estiver programando no Visual Basic, poderá usar a CBool
função para converter a representação de cadeia de caracteres de um número em um valor booliano. "0" é convertido false
em e a representação de cadeia de caracteres de qualquer valor diferente de zero é convertida em true
. Se você não estiver programando no Visual Basic, deverá converter sua cadeia de caracteres numérica em um número antes de convertê-la em um booliano. O exemplo a seguir ilustra isso convertendo uma matriz de inteiros em valores boolianos.
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
Comparar valores boolianos
Como os true
valores boolianos são ou false
, há pouco motivo para chamar explicitamente o CompareTo método , o que indica se uma instância é maior que, menor ou igual a um valor especificado. Normalmente, para comparar duas variáveis boolianas, chame o método ou use o Equals operador de igualdade da linguagem.
No entanto, quando você deseja comparar uma variável booliana com o valor true
booliano literal ou false
, não é necessário fazer uma comparação explícita, pois o resultado da avaliação de um valor booliano é esse valor booliano. Por exemplo, as expressões
if (booleanValue == true) {
if booleanValue = true then
If booleanValue = True Then
e
if (booleanValue) {
if booleanValue then
If booleanValue Then
são equivalentes, mas o segundo é mais compacto. No entanto, ambas as técnicas oferecem desempenho comparável.
Trabalhar com boolianos como valores binários
Um valor booliano ocupa um byte de memória, como mostra o exemplo C# ou F# a seguir. O exemplo de C# deve ser compilado com a opção /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
O bit de ordem baixa do byte é usado para representar seu valor. Um valor de 1 representa true
; um valor de 0 representa false
.
Dica
Você pode usar a System.Collections.Specialized.BitVector32 estrutura para trabalhar com conjuntos de valores boolianos.
Você pode converter um valor booliano em sua representação binária chamando o BitConverter.GetBytes(Boolean) método . O método retorna uma matriz de bytes com um único elemento. Para restaurar um valor booliano de sua representação binária, você pode chamar o BitConverter.ToBoolean(Byte[], Int32) método .
O exemplo a seguir chama o BitConverter.GetBytes método para converter um valor booliano em sua representação binária e exibe os bits individuais do valor e, em seguida, chama o BitConverter.ToBoolean método para restaurar o valor de sua representação binária.
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
Executar operações com valores boolianos
Esta seção ilustra como os valores boolianos são usados em aplicativos. A primeira seção discute seu uso como um sinalizador. O segundo ilustra seu uso para operações aritméticas.
Valores boolianos como sinalizadores
Variáveis boolianas são mais comumente usadas como sinalizadores, para sinalizar a presença ou ausência de alguma condição. Por exemplo, no String.Compare(String, String, Boolean) método , o parâmetro final, ignoreCase
, é um sinalizador que indica se a comparação de duas cadeias de caracteres não diferencia maiúsculas de minúsculas (ignoreCase
é true
) ou diferencia maiúsculas de minúsculas (ignoreCase
é false
). O valor do sinalizador pode ser avaliado em uma instrução condicional.
O exemplo a seguir usa um aplicativo de console simples para ilustrar o uso de variáveis boolianas como sinalizadores. O aplicativo aceita parâmetros de linha de comando que permitem que a saída seja redirecionada para um arquivo especificado (a opção /f
) e que permitem que a saída seja enviada para um arquivo especificado e para o console (a opção /b
). O aplicativo define um sinalizador chamado isRedirected
para indicar se a saída deve ser enviada para um arquivo e um sinalizador chamado isBoth
para indicar que a saída deve ser enviada para o console. Observe que o exemplo F# usa uma função recursiva para analisar os argumentos.
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
Boolianos e operações aritméticas
Às vezes, um valor booliano é usado para indicar a presença de uma condição que dispara um cálculo matemático. Por exemplo, uma hasShippingCharge
variável pode servir como um sinalizador para indicar se é necessário adicionar encargos de envio a um valor da fatura.
Como uma operação com um false
valor não tem efeito sobre o resultado de uma operação, não é necessário converter o booliano em um valor integral a ser usado na operação matemática. Em vez disso, você pode usar a lógica condicional.
O exemplo a seguir calcula um valor que consiste em um subtotal, uma cobrança de remessa e uma taxa de serviço opcional. A hasServiceCharge
variável determina se o preço do serviço é aplicado. Em vez de converter hasServiceCharge
em um valor numérico e multiplicá-lo pela quantidade do encargo de serviço, o exemplo usa a lógica condicional para adicionar o valor da cobrança do serviço se for aplicável.
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.
Boolianos e interoperabilidade
Embora o marshaling de tipos de dados base para COM seja geralmente simples, o Boolean tipo de dados é uma exceção. Você pode aplicar o MarshalAsAttribute atributo para realizar marshaling do Boolean tipo em qualquer uma das seguintes representações:
Tipo de enumeração | Formato não gerenciado |
---|---|
UnmanagedType.Bool | Um valor inteiro de 4 bytes, em que qualquer valor diferente de zero representa true e 0 representa false . Esse é o formato padrão de um Boolean campo em uma estrutura e de um Boolean parâmetro em chamadas de invocação de plataforma. |
UnmanagedType.U1 | Um valor inteiro de 1 byte, em que o 1 representa true e 0 representa false . |
UnmanagedType.VariantBool | Um valor inteiro de 2 bytes, em que -1 representa true e 0 representa false . Esse é o formato padrão de um Boolean parâmetro em chamadas de interoperabilidade COM. |
Campos
FalseString |
Representa o valor booliano |
TrueString |
Representa o valor booliano |
Métodos
CompareTo(Boolean) |
Compara essa instância com um objeto Boolean especificado e retorna um inteiro que indica a relação entre eles. |
CompareTo(Object) |
Compara essa instância com um objeto especificado e retorna um inteiro que indica a relação entre eles. |
Equals(Boolean) |
Retorna um valor que indica se essa instância é igual a um objeto Boolean especificado. |
Equals(Object) |
Retorna um valor que indica se a instância é igual a um objeto especificado. |
GetHashCode() |
Retorna o código hash para a instância. |
GetTypeCode() |
Retorna o código de tipo para o tipo de valor Boolean. |
Parse(ReadOnlySpan<Char>) |
Converte a representação de intervalo especificada de um valor lógico para seu Boolean equivalente. |
Parse(String) |
Converte a representação de cadeia de caracteres especificada de um valor lógico em seu Boolean equivalente. |
ToString() |
Converte o valor dessa instância na representação da cadeia de caracteres equivalente ("True" ou "False"). |
ToString(IFormatProvider) |
Converte o valor dessa instância na representação da cadeia de caracteres equivalente ("True" ou "False"). |
TryFormat(Span<Char>, Int32) |
Tenta formatar o valor da instância booliana atual para o intervalo de caracteres fornecido. |
TryParse(ReadOnlySpan<Char>, Boolean) |
Tenta converter a representação de intervalo especificada de um valor lógico em seu Boolean equivalente. |
TryParse(String, Boolean) |
Tenta converter a representação de cadeia de caracteres especificada de um valor lógico em seu Boolean equivalente. |
Implantações explícitas de interface
IComparable.CompareTo(Object) |
Compara a instância atual com outro objeto do mesmo tipo e retorna um inteiro que indica se a instância atual precede, segue ou ocorre na mesma posição da ordem de classificação do outro objeto. |
IConvertible.GetTypeCode() |
Retorna o TypeCode para essa instância. |
IConvertible.ToBoolean(IFormatProvider) |
Para obter uma descrição desse membro, confira ToBoolean(IFormatProvider). |
IConvertible.ToByte(IFormatProvider) |
Para obter uma descrição desse membro, confira ToByte(IFormatProvider). |
IConvertible.ToChar(IFormatProvider) |
Não há suporte para esta conversão. A tentativa de usar esse método lança um InvalidCastException. |
IConvertible.ToDateTime(IFormatProvider) |
Não há suporte para esta conversão. A tentativa de usar esse método lança um InvalidCastException. |
IConvertible.ToDecimal(IFormatProvider) |
Para obter uma descrição desse membro, confira ToDecimal(IFormatProvider). |
IConvertible.ToDouble(IFormatProvider) |
Para obter uma descrição desse membro, confira ToDouble(IFormatProvider). |
IConvertible.ToInt16(IFormatProvider) |
Para obter uma descrição desse membro, confira ToInt16(IFormatProvider). |
IConvertible.ToInt32(IFormatProvider) |
Para obter uma descrição desse membro, confira ToInt32(IFormatProvider). |
IConvertible.ToInt64(IFormatProvider) |
Para obter uma descrição desse membro, confira ToInt64(IFormatProvider). |
IConvertible.ToSByte(IFormatProvider) |
Para obter uma descrição desse membro, confira ToSByte(IFormatProvider). |
IConvertible.ToSingle(IFormatProvider) |
Para obter uma descrição desse membro, confira ToSingle(IFormatProvider). |
IConvertible.ToString(IFormatProvider) |
Converte o valor dessa instância em uma cadeia de caracteres equivalente, usando as informações de formatação específicas da cultura especificadas. |
IConvertible.ToType(Type, IFormatProvider) |
Para obter uma descrição desse membro, confira ToType(Type, IFormatProvider). |
IConvertible.ToUInt16(IFormatProvider) |
Para obter uma descrição desse membro, confira ToUInt16(IFormatProvider). |
IConvertible.ToUInt32(IFormatProvider) |
Para obter uma descrição desse membro, confira ToUInt32(IFormatProvider). |
IConvertible.ToUInt64(IFormatProvider) |
Para obter uma descrição desse membro, confira ToUInt64(IFormatProvider). |
IParsable<Boolean>.Parse(String, IFormatProvider) |
Analisa uma cadeia de caracteres em um valor. |
IParsable<Boolean>.TryParse(String, IFormatProvider, Boolean) |
Representa um valor booliano ( |
ISpanParsable<Boolean>.Parse(ReadOnlySpan<Char>, IFormatProvider) |
Analisa um intervalo de caracteres em um valor. |
ISpanParsable<Boolean>.TryParse(ReadOnlySpan<Char>, IFormatProvider, Boolean) |
Representa um valor booliano ( |
Aplica-se a
Acesso thread-safe
Todos os membros desse tipo são thread-safe. Os membros que aparentam modificar efetivamente o estado retornam uma nova instância inicializada com o novo valor. Assim como acontece com qualquer outro tipo, a leitura e a gravação em uma variável compartilhada que contém uma instância desse tipo devem ser protegidas por um bloqueio para garantir thread-safe.
Comentários
Enviar e exibir comentários de