다음을 통해 공유


System.Boolean 구조체

이 문서는 이 API에 대한 참조 설명서를 보충하는 추가 설명을 제공합니다.

Boolean 인스턴스는 true 또는 false두 값 중 하나를 가질 수 있습니다.

Boolean 구조는 다음 작업을 지원하는 메서드를 제공합니다.

이 문서에서는 이러한 작업 및 기타 사용량 세부 정보를 설명합니다.

부울 값 서식 지정

Boolean 문자열 표현은 true 값의 경우 "True"이고 false 값의 경우 "False"입니다. Boolean 값의 문자열 표현은 읽기 전용 TrueStringFalseString 필드에 의해 정의됩니다.

ToString 메서드를 사용하여 부울 값을 문자열로 변환합니다. 부울 구조에는 매개 변수가 없는 ToString 메서드와 서식을 제어하는 매개 변수를 포함하는 ToString() 메서드의 두 가지 ToString(IFormatProvider) 오버로드가 포함됩니다. 그러나 이 매개 변수는 무시되므로 두 오버로드는 동일한 문자열을 생성합니다. ToString(IFormatProvider) 메서드는 문화권 구분 서식을 지원하지 않습니다.

다음 예제에서는 ToString 메서드를 사용하여 서식을 지정하는 방법을 보여 줍니다. C# 및 VB 예제에서는 복합 서식 지정 기능을 사용하고 F# 예제에서는 문자열 보간사용합니다. 두 경우 모두 ToString 메서드가 암시적으로 호출됩니다.

using System;

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

      Console.WriteLine($"It is raining: {raining}");
      Console.WriteLine($"The bus is late: {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

Boolean 구조에는 두 개의 값만 있을 수 있으므로 사용자 지정 서식을 쉽게 추가할 수 있습니다. 다른 문자열 리터럴이 "True" 및 "False"로 대체되는 간단한 사용자 지정 서식의 경우 C#의 조건부 연산자 또는 Visual Basic에서 If 연산자와 같이 언어에서 지원하는 조건부 평가 기능을 사용할 수 있습니다. 다음 예제에서는 이 기술을 사용하여 Boolean 값의 서식을 "True" 및 "False"가 아닌 "예" 및 "아니요"로 지정합니다.

using System;

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

        Console.WriteLine($"It is raining: {(raining ? "Yes" : "No")}");
        Console.WriteLine($"The bus is late: {(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

문화권 구분 서식을 포함하여 더 복잡한 사용자 지정 서식 지정 작업의 경우 String.Format(IFormatProvider, String, Object[]) 메서드를 호출하고 ICustomFormatter 구현을 제공할 수 있습니다. 다음 예제에서는 ICustomFormatterIFormatProvider 인터페이스를 구현하여 영어(미국), 프랑스어(프랑스) 및 러시아어(러시아) 문화권에 문화권 구분 부울 문자열을 제공합니다.

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': верно

선택적으로, 리소스 파일을 사용하여 특정 문화에 맞는 부울 문자열을 정의할 수 있습니다.

부울 값으로 변환 및 변환 해제

Boolean 구조체는 IConvertible 인터페이스를 구현합니다. 따라서 Convert 클래스를 사용하여 Boolean 값과 .NET의 다른 기본 형식 간에 변환을 수행하거나 Boolean 구조체의 명시적 구현을 호출할 수 있습니다. 그러나 Boolean과 다음 형식 간의 변환은 지원되지 않으므로 해당 변환 메서드가 InvalidCastException 예외를 발생시킵니다.

모든 정수 또는 부동 소수점 숫자를 부울 값으로 변환할 때, 0이 아닌 값은 true으로, 0 값은 false로 변환됩니다. 다음 예제에서는 Convert.ToBoolean 클래스의 선택한 오버로드를 호출하여 이를 보여 줍니다.

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

Boolean에서 숫자 값으로 변환할 때, Convert 클래스의 변환 메소드는 true을 1로 변환하고 false를 0으로 변환합니다. 그러나 Visual Basic 변환 함수는 true 255(Byte 값으로 변환하는 경우) 또는 -1(다른 모든 숫자 변환의 경우)로 변환합니다. 다음 예제에서는 true 메서드를 사용하여 Convert 숫자 값으로 변환하고, Visual Basic 예제의 경우 Visual Basic 언어의 고유한 변환 연산자를 사용합니다.

using System;

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

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

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

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

      int intValue;
      intValue = Convert.ToInt32(flag);
      Console.WriteLine($"{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)

Boolean 문자열 값으로의 변환은 서식 부울 값 섹션을 참조하세요. 문자열에서 Boolean 값으로 변환하려면 부울 값 구문 분석 섹션을 참조하세요.

부울 값 구문 분석

Boolean 구조에는 문자열을 부울 값으로 변환하는 ParseTryParse두 개의 정적 구문 분석 메서드가 포함됩니다. 부울 값의 문자열 표현은 각각 "True" 및 "False"인 TrueStringFalseString 필드 값의 대/소문자를 구분하지 않는 값으로 정의됩니다. 즉, 성공적으로 구문 분석할 수 있는 문자열은 "True", "False", "true", "false" 또는 어떤 대소문자 조합의 동등한 문자열입니다. "0" 또는 "1"과 같은 숫자 문자열을 구문 분석할 수 없습니다. 문자열 비교를 수행할 때 선행 또는 후행 공백 문자는 고려되지 않습니다.

다음 예제에서는 ParseTryParse 메서드를 사용하여 여러 문자열을 구문 분석합니다. 대/소문자를 구분하지 않는 "True" 및 "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($"'{value}' --> {flag}");
         }
         catch (ArgumentException) {
            Console.WriteLine("Cannot parse a null string.");
         }
         catch (FormatException) {
            Console.WriteLine($"Cannot parse '{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($"'{value}' --> {flag}");
         else
            Console.WriteLine($"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'
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'

Visual Basic에서 프로그래밍하는 경우 CBool 함수를 사용하여 숫자의 문자열 표현을 부울 값으로 변환할 수 있습니다. "0"은 false변환되고 0이 아닌 값의 문자열 표현은 true변환됩니다. Visual Basic에서 프로그래밍하지 않는 경우, 숫자 문자열을 부울로 변환하기 전에 먼저 숫자로 변환해야 합니다. 다음 예제에서는 정수 배열을 부울 값으로 변환하여 이를 보여 줍니다.

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 '{value}' to {result}");
         }
         else {
            Console.WriteLine($"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
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

부울 값 비교

부울 값은 true 또는 false때문에 인스턴스가 지정된 값보다 크거나 작거나 같은지 여부를 나타내는 CompareTo 메서드를 명시적으로 호출할 이유가 거의 없습니다. 일반적으로 두 부울 변수를 비교하려면 Equals 메서드를 호출하거나 언어의 같음 연산자를 사용합니다.

그러나 부울 변수를 리터럴 부울 값 true 또는 false비교하려는 경우 부울 값을 계산한 결과가 부울 값이므로 명시적 비교를 수행할 필요가 없습니다. 예를 들어 다음 두 식은 동일하지만 두 번째 식은 더 간결합니다. 그러나 두 기술 모두 비슷한 성능을 제공합니다.

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

부울 값을 이진 형태로 다루기

부울 값은 다음 예제와 같이 1 바이트 메모리를 차지합니다. C# 예제는 /unsafe 스위치를 사용하여 컴파일해야 합니다.

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: {sizeof(BoolStruct)}");
         Console.WriteLine("Field offsets:");
         Console.WriteLine($"   flag1: {(bool*) &b.flag1 - addr}");
         Console.WriteLine($"   flag1: {(bool*) &b.flag2 - addr}");
         Console.WriteLine($"   flag1: {(bool*) &b.flag3 - addr}");
         Console.WriteLine($"   flag1: {(bool*) &b.flag4 - addr}");
         Console.WriteLine($"   flag1: {(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

바이트의 하위 비트는 해당 값을 나타내는 데 사용됩니다. 값이 1이면 true; 값이 0이면 false나타냅니다.

팁 (조언)

System.Collections.Specialized.BitVector32 구조를 사용하여 부울 값 집합과 작업을 수행할 수 있습니다.

BitConverter.GetBytes(Boolean) 메서드를 호출하여 부울 값을 이진 표현으로 변환할 수 있습니다. 메서드는 단일 요소가 있는 바이트 배열을 반환합니다. 이진 표현에서 부울 값을 복원하려면 BitConverter.ToBoolean(Byte[], Int32) 메서드를 호출할 수 있습니다.

다음 예제에서는 BitConverter.GetBytes 메서드를 호출하여 부울 값을 이진 표현으로 변환하고 값의 개별 비트를 표시한 다음 BitConverter.ToBoolean 메서드를 호출하여 이진 표현에서 값을 복원합니다.

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: {flag}");
            Console.WriteLine($"Binary value:   {value} ({GetBinaryString(value)})");
            // Restore the flag from its binary representation.
            bool newFlag = BitConverter.ToBoolean(new Byte[] { value }, 0);
            Console.WriteLine($"Restored value: {flag}{Environment.NewLine}");
        }
    }

    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

부울 값을 사용하여 연산 수행

이 섹션에서는 앱에서 부울 값을 사용하는 방법을 보여 줍니다. 첫 번째 섹션에서는 플래그로 사용하는 것을 설명합니다. 두 번째는 산술 연산에 사용하는 방법을 보여 줍니다.

불리언 값을 플래그로 사용하기

부울 변수는 가장 일반적으로 플래그로 사용되어 일부 조건의 존재 여부 또는 부재를 알릴 수 있습니다. 예를 들어 String.Compare(String, String, Boolean) 메서드에서 ignoreCase마지막 매개 변수는 두 문자열의 비교가 대/소문자를 구분하지 않는지(ignoreCasetrue) 또는 대/소문자 구분(ignoreCasefalse)인지를 나타내는 플래그입니다. 그런 다음 조건문에서 플래그 값을 평가할 수 있습니다.

다음 예제에서는 간단한 콘솔 앱을 사용하여 부울 변수를 플래그로 사용하는 방법을 보여 줍니다. 앱은 출력을 지정된 파일(/f 스위치)으로 리디렉션할 수 있도록 하고 출력을 지정된 파일과 콘솔(/b 스위치)으로 보낼 수 있도록 하는 명령줄 매개 변수를 허용합니다. 앱은 출력을 파일로 보낼지 여부를 나타내는 isRedirected 플래그와 출력을 콘솔로 보내야 함을 나타내는 isBoth 플래그를 정의합니다. F# 예제에서는 재귀 함수 사용하여 인수를 구문 분석합니다.

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

부울 및 산술 연산

부울 값은 가끔 수학 계산을 유발하는 조건의 존재를 나타내는 데 사용됩니다. 예를 들어 hasShippingCharge 변수는 송장 금액에 배송 요금을 추가할지 여부를 나타내는 플래그로 사용될 수 있습니다.

false 값과의 연산은 결과에 영향을 미치지 않으므로, 부울(Boolean)을 수학적 연산에 사용할 정수 값으로 변환할 필요가 없습니다. 대신 조건부 논리를 사용할 수 있습니다.

다음 예제에서는 부분합, 배송 요금 및 선택적 서비스 요금으로 구성된 금액을 계산합니다. hasServiceCharge 변수는 서비스 요금이 적용되는지 여부를 결정합니다. 이 예제에서는 hasServiceCharge 숫자 값으로 변환하고 서비스 요금의 양을 곱하는 대신 조건부 논리를 사용하여 서비스 요금 금액을 적용할 수 있는 경우 추가합니다.

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 = {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.
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.

부울 및 interop

기본 데이터 형식을 COM으로 마샬링하는 것은 일반적으로 간단하지만 Boolean 데이터 형식은 예외입니다. MarshalAsAttribute 특성을 적용하여 Boolean 형식을 다음 표현으로 마샬링할 수 있습니다.

열거형 형식 관리되지 않는 형식
UnmanagedType.Bool 0이 아닌 값이 true 나타내고 0이 false나타내는 4바이트 정수 값입니다. 이는 구조체의 Boolean 필드와 플랫폼 호출에서 Boolean 매개 변수의 기본 형식입니다.
UnmanagedType.U1 1은 true 나타내고 0은 false나타내는 1 바이트 정수 값입니다.
UnmanagedType.VariantBool 2 바이트 정수 값입니다. 여기서 -1 true 나타내고 0은 false나타냅니다. COM interop 호출에서 Boolean 매개 변수의 기본 형식입니다.