Boolean 구조체

정의

부울(true 또는 false) 값을 나타냅니다.

public value class bool : IComparable, IComparable<bool>, IConvertible, IEquatable<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>
[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
[<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, IConvertible
Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IEquatable(Of Boolean)
상속
Boolean
특성
구현

설명

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

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

다음 섹션에서는 이러한 작업 및 기타 사용 세부 정보에 대해 설명 합니다.

부울 값 서식 지정

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

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

다음 예제에서는 메서드를 사용 하 여 형식을 지정 하는 방법을 보여 줍니다 ToString . 이 예제에서는 복합 서식 지정 기능을 사용 하므로 ToString 메서드가 암시적으로 호출 됩니다.

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
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

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

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

문화권 구분 형식 지정을 비롯 한 보다 복잡 한 사용자 지정 서식 지정 작업을 수행 하려면 메서드를 호출 String.Format(IFormatProvider, String, Object[]) 하 고 ICustomFormatter 구현을 제공 합니다. 다음 예제에서는 ICustomFormatter 및 인터페이스를 구현 IFormatProvider 하 여 영어 (미국), 프랑스어 (프랑스) 및 러시아어 (러시아) 문화권에 대 한 문화권 구분 부울 문자열을 제공 합니다.

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

필요에 따라 리소스 파일 을 사용 하 여 문화권별 부울 문자열을 정의할 수 있습니다.

부울 값으로 변환

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

정수 계열 또는 부동 소수점 숫자를 부울 값으로 변환 하면 0이 아닌 값을로, 0이 아닌 값을로 변환 true false 합니다. 다음 예제에서는 클래스의 선택 된 오버 로드를 호출 하 여이를 보여 줍니다 Convert.ToBoolean .

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
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

부울에서 숫자 값으로 변환 하는 경우 클래스의 변환 메서드는 Convert true 1과 0으로 변환 false 됩니다. 그러나 Visual Basic 변환 함수는 true 255 (값 변환의 경우 Byte ) 또는-1 (기타 모든 숫자 변환의 경우)으로 변환 됩니다. 다음 예제에서는 true 메서드를 사용 하 여 숫자 값으로 변환 하 Convert 고 Visual Basic 예제에서는 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
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)

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

부울 값 구문 분석

구조체에는 Boolean Parse TryParse 문자열을 부울 값으로 변환 하는 두 개의 정적 구문 분석 메서드인 및가 포함 되어 있습니다. 부울 값의 문자열 표현은 TrueString FalseString 각각 "True" 및 "False" 인 및 필드 값의 대/소문자를 구분 하지 않는 값으로 정의 됩니다. 즉, 성공적으로 구문 분석 하는 문자열은 "True", "False", "True", "False" 또는 일부 혼합 case와 동일 합니다. 숫자 문자열 (예: "0" 또는 "1")은 성공적으로 구문 분석할 수 없습니다. 문자열 비교를 수행할 때 선행 또는 후행 공백 문자는 고려 되지 않습니다.

다음 예제에서는 및 메서드를 사용 하 여 Parse TryParse 여러 문자열을 구문 분석 합니다. "True" 및 "False"의 대/소문자를 구분 하지 않는 항목은 구문 분석할 수 있습니다.

using System;

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

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

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
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

부울 값 비교

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

그러나 부울 변수를 리터럴 부울 값 또는와 비교 하려는 경우에는 true false 부울 값을 평가한 결과가 부울 값 이기 때문에 명시적 비교를 수행할 필요가 없습니다. 예를 들어 식은

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

그리고

if (booleanValue) {
If booleanValue Then

는 동일 하지만 두 번째는 더 간결 합니다. 그러나 두 기술 모두 비슷한 성능을 제공 합니다.

부울을 이진 값으로 사용

다음 c # 예제와 같이 부울 값은 1 바이트의 메모리를 차지 합니다. 이 예제는 스위치를 사용 하 여 컴파일해야 합니다 /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

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

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

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

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

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
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

부울 값을 사용 하 여 작업 수행

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

부울 값 (플래그)

부울 변수는 특정 조건 유무를 알리기 위해 가장 일반적으로 플래그로 사용 됩니다. 예를 들어 String.Compare(String, String, Boolean) 메서드에서 최종 매개 변수는 ignoreCase 두 문자열의 비교에서 대/소문자를 구분 하지 않는지 ( ignoreCase is true ) 또는 대/소문자를 구분 하는지 ( ignoreCase is) 여부를 나타내는 플래그입니다 false . 그런 다음 조건문에서 플래그의 값을 계산할 수 있습니다.

다음 예에서는 간단한 콘솔 앱을 사용 하 여 부울 변수를 플래그로 사용 하는 방법을 보여 줍니다. 앱은 출력을 지정 된 파일 (스위치)로 리디렉션할 수 있도록 하는 명령줄 매개 변수를 허용 /f 하며, 출력을 지정 된 파일과 콘솔 (스위치) 모두로 보낼 수 있도록 합니다 /b . 앱은 출력을 파일로 보낼지 여부를 나타내는 이라는 플래그를 정의 하 isRedirected 고, 이라는 플래그를 정의 하 여 isBoth 출력을 콘솔에 보내야 함을 나타냅니다.

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");
   }
}
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

부울 및 산술 연산

부울 값은 수학적 계산을 트리거하는 조건이 있는지 여부를 나타내는 데 사용 되는 경우도 있습니다. 예를 들어 hasShippingCharge 변수는 송장 금액에 배송 요금을 추가할지 여부를 나타내는 플래그로 사용할 수 있습니다.

값을 사용 하는 작업은 false 연산 결과에 영향을 주지 않으므로 부울을 수치 연산에서 사용할 정수 계열 값으로 변환할 필요가 없습니다. 대신 조건부 논리를 사용할 수 있습니다.

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

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

부울 및 interop

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

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

필드

FalseString

부울 값 false를 문자열로 나타냅니다. 이 필드는 읽기 전용입니다.

TrueString

부울 값 true를 문자열로 나타냅니다. 이 필드는 읽기 전용입니다.

메서드

CompareTo(Boolean)

이 인스턴스와 지정된 Boolean 개체를 비교하고 서로의 관계를 나타내는 정수를 반환합니다.

CompareTo(Object)

이 인스턴스와 지정된 개체를 비교하고 서로의 관계를 나타내는 정수를 반환합니다.

Equals(Boolean)

이 인스턴스가 지정된 Boolean 개체와 같은지 표시하는 값을 반환합니다.

Equals(Object)

이 인스턴스가 지정된 개체와 같은지를 표시하는 값을 반환합니다.

GetHashCode()

이 인스턴스의 해시 코드를 반환합니다.

GetTypeCode()

Boolean 값 형식에 대한 형식 코드를 반환합니다.

Parse(ReadOnlySpan<Char>)

논리 값의 지정된 범위 표현을 해당하는 Boolean으로 변환합니다.

Parse(String)

논리 값의 지정된 문자열 표현을 해당하는 Boolean 값으로 변환합니다.

ToString()

이 인스턴스의 값을 해당하는 문자열 표현("True" 또는 "False")으로 변환합니다.

ToString(IFormatProvider)

이 인스턴스의 값을 해당하는 문자열 표현("True" 또는 "False")으로 변환합니다.

TryFormat(Span<Char>, Int32)

현재 boolean 인스턴스 값의 형식을 제공된 문자 범위로 지정하려고 시도합니다.

TryParse(ReadOnlySpan<Char>, Boolean)

논리 값의 지정된 범위 표현을 해당하는 Boolean으로 변환하려고 시도합니다.

TryParse(String, Boolean)

논리 값의 지정된 문자열 표현을 해당하는 Boolean으로 변환하려고 시도합니다.

명시적 인터페이스 구현

IComparable.CompareTo(Object)

현재 인스턴스와 동일한 형식의 다른 개체를 비교하고 정렬 순서에서 현재 인스턴스의 위치가 다른 개체보다 앞인지, 뒤인지 또는 동일한지를 나타내는 정수를 반환합니다.

IConvertible.GetTypeCode()

이 인스턴스에 대한 TypeCode를 반환합니다.

IConvertible.ToBoolean(IFormatProvider)

이 멤버에 대한 설명은 ToBoolean(IFormatProvider)를 참조하세요.

IConvertible.ToByte(IFormatProvider)

이 멤버에 대한 설명은 ToByte(IFormatProvider)를 참조하세요.

IConvertible.ToChar(IFormatProvider)

이 변환은 지원되지 않습니다. 이 메서드를 사용하려고 하면 InvalidCastException이 throw됩니다.

IConvertible.ToDateTime(IFormatProvider)

이 변환은 지원되지 않습니다. 이 메서드를 사용하려고 하면 InvalidCastException이 throw됩니다.

IConvertible.ToDecimal(IFormatProvider)

이 멤버에 대한 설명은 ToDecimal(IFormatProvider)를 참조하세요.

IConvertible.ToDouble(IFormatProvider)

이 멤버에 대한 설명은 ToDouble(IFormatProvider)를 참조하세요.

IConvertible.ToInt16(IFormatProvider)

이 멤버에 대한 설명은 ToInt16(IFormatProvider)를 참조하세요.

IConvertible.ToInt32(IFormatProvider)

이 멤버에 대한 설명은 ToInt32(IFormatProvider)를 참조하세요.

IConvertible.ToInt64(IFormatProvider)

이 멤버에 대한 설명은 ToInt64(IFormatProvider)를 참조하세요.

IConvertible.ToSByte(IFormatProvider)

이 멤버에 대한 설명은 ToSByte(IFormatProvider)를 참조하세요.

IConvertible.ToSingle(IFormatProvider)

이 멤버에 대한 설명은 ToSingle(IFormatProvider)를 참조하세요.

IConvertible.ToString(IFormatProvider)

지정된 문화권별 형식 지정 정보를 사용하여 이 인스턴스의 값을 해당하는 문자열로 변환합니다.

IConvertible.ToType(Type, IFormatProvider)

이 멤버에 대한 설명은 ToType(Type, IFormatProvider)를 참조하세요.

IConvertible.ToUInt16(IFormatProvider)

이 멤버에 대한 설명은 ToUInt16(IFormatProvider)를 참조하세요.

IConvertible.ToUInt32(IFormatProvider)

이 멤버에 대한 설명은 ToUInt32(IFormatProvider)를 참조하세요.

IConvertible.ToUInt64(IFormatProvider)

이 멤버에 대한 설명은 ToUInt64(IFormatProvider)를 참조하세요.

적용 대상

스레드 보안

이 형식의 모든 멤버는 스레드로부터 안전 합니다. 인스턴스 상태를 수정 하는 것 처럼 보이는 멤버는 실제로 새 값으로 초기화 된 새 인스턴스를 반환 합니다. 다른 형식과 마찬가지로이 형식의 인스턴스를 포함 하는 공유 변수에 대 한 읽기 및 쓰기는 스레드 안전을 보장 하기 위해 잠금으로 보호 되어야 합니다.