Boolean 구조체
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
부울(true
또는 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)
- 상속
- 특성
- 구현
설명
Boolean instance 또는 의 두 값 true
false
중 하나를 가질 수 있습니다.
구조체는 Boolean 다음 작업을 지원하는 메서드를 제공합니다.
다음 섹션에서는 이러한 작업 및 기타 사용량 세부 정보를 설명합니다.
부울 값 서식 지정
의 문자열 표현은 값의 Boolean 경우 "True"이거나 값의 true
경우 "False"입니다 false
. 값의 Boolean 문자열 표현은 읽기 전용 TrueString 및 FalseString 필드에 의해 정의됩니다.
메서드를 ToString 사용하여 부울 값을 문자열로 변환합니다. 부울 구조에는 매개 변수 없는 ToString() 메서드와 ToString(IFormatProvider) 서식을 제어하는 매개 변수를 포함하는 메서드의 두 오버 ToString 로드가 포함됩니다. 그러나 이 매개 변수는 무시되므로 두 오버로드는 동일한 문자열을 생성합니다. 메서드는 ToString(IFormatProvider) 문화권을 구분하는 서식을 지원하지 않습니다.
다음 예제에서는 메서드를 사용하여 서식을 지정하는 방법을 보여 줍니다 ToString . C# 및 VB 예제에서는 복합 서식 지정 기능을 사용하고 F# 예제는 문자열 보간을 사용합니다. 두 경우 모두 메서드가 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
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
구조체에는 Boolean 두 개의 값만 있을 수 있으므로 사용자 지정 서식을 쉽게 추가할 수 있습니다. 다른 문자열 리터럴이 "True" 및 "False"로 대체되는 간단한 사용자 지정 서식의 경우 C#의 조건부 연산자 또는 Visual Basic의 If 연산 자와 같이 언어에서 지원하는 조건부 평가 기능을 사용할 수 있습니다. 다음 예제에서는 이 기술을 사용하여 값을 "True" 및 "False"가 아닌 "예" 및 "아니요"로 서식을 지정 Boolean 합니다.
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
문화권에 민감한 서식 지정을 포함하여 보다 복잡한 사용자 지정 서식 지정 작업의 경우 메서드를 String.Format(IFormatProvider, String, Object[]) 호출하고 구현을 ICustomFormatter 제공할 수 있습니다. 다음 예제에서는 및 IFormatProvider 인터페이스를 ICustomFormatter 구현하여 영어(미국), 프랑스어(프랑스) 및 러시아어(러시아) 문화권에 대해 문화권에 민감한 부울 문자열을 제공합니다.
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': верно
필요에 따라 리소스 파일을 사용하여 문화권별 부울 문자열을 정의할 수 있습니다.
부울 값으로 변환
구조체는 Boolean 인터페이스를 IConvertible 구현합니다. 따라서 클래스를 Convert 사용하여 값과 .NET의 다른 기본 형식 간에 Boolean 변환을 수행하거나 구조체의 명시적 구현을 Boolean 호출할 수 있습니다. 그러나 와 다음 형식 간의 Boolean 변환은 지원되지 않으므로 해당 변환 메서드는 예외를 throw합니다 InvalidCastException .
및 (Convert.ToBoolean(Char)및 CharConvert.ToChar(Boolean) 메서드) 간의 Boolean 변환
및 (Convert.ToBoolean(DateTime)및 DateTimeConvert.ToDateTime(Boolean) 메서드) 간의 Boolean 변환
정수 또는 부동 소수점 숫자에서 부울 값으로의 모든 변환은 0이 아닌 값을 로 true
변환하고 0 값을 로 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
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
부울에서 숫자 값으로 변환할 때 클래스의 변환 메서드는 Convert 1 및 false
0으로 변환 true
됩니다. 그러나 Visual Basic 변환 함수는 255(값으로 변환 Byte 의 경우) 또는 -1(다른 모든 숫자 변환의 경우)으로 변환 true
됩니다. 다음 예제에서는 메서드를 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
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)
에서 Boolean 문자열 값으로 변환하려면 부울 값 서식 지정 섹션을 참조하세요 . 문자열에서 값으로 Boolean 의 변환은 부울 값 구문 분석 섹션을 참조하세요 .
부울 값 구문 분석
구조체에는 Boolean 문자열을 부울 값으로 변환하는 두 개의 정적 구문 분석 메서드 Parse 와 TryParse가 포함됩니다. 부울 값의 문자열 표현은 각각 "True" 및 "False"인 및 FalseString 필드 값의 TrueString 대/소문자를 구분하지 않는 값으로 정의됩니다. 즉, 성공적으로 구문 분석하는 유일한 문자열은 "True", "False", "true", "false" 또는 일부 혼합 대/소문자입니다. "0" 또는 "1"과 같은 숫자 문자열을 구문 분석할 수 없습니다. 문자열 비교를 수행할 때 선행 또는 후행 공백 문자는 고려되지 않습니다.
다음 예제에서는 및 TryParse 메서드를 사용하여 Parse 여러 문자열을 구문 분석합니다. 대/소문자를 구분하지 않는 "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'
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'
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
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
부울 값 비교
부울 값은 또는 false
이므로 true
메서드를 명시적으로 호출 CompareTo 할 이유가 거의 없습니다. 이 메서드는 instance 지정된 값보다 크거나 작거나 같은지 여부를 나타냅니다. 일반적으로 두 부울 변수를 비교하려면 메서드를 Equals 호출하거나 언어의 같음 연산자를 사용합니다.
그러나 부울 변수를 리터럴 부울 값 또는 false
와 비교하려는 경우 부울 값을 계산한 결과가 부울 값 true
이므로 명시적 비교를 수행할 필요가 없습니다. 예를 들어 식
if (booleanValue == true) {
if booleanValue = true then
If booleanValue = True Then
그리고
if (booleanValue) {
if booleanValue then
If booleanValue Then
은 동일하지만 두 번째는 더 작습니다. 그러나 두 기술 모두 비슷한 성능을 제공합니다.
부울을 이진 값으로 작업
다음 C# 또는 F# 예제와 같이 부울 값은 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 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
바이트의 하위 비트는 해당 값을 나타내는 데 사용됩니다. 값 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
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
부울 값을 사용하여 작업 수행
이 섹션에서는 앱에서 부울 값을 사용하는 방법을 보여 줍니다. 첫 번째 섹션에서는 플래그로 사용하는 것을 설명합니다. 두 번째는 산술 연산에 대한 사용을 보여 줍니다.
부울 값을 플래그로
부울 변수는 가장 일반적으로 플래그로 사용되어 일부 조건의 존재 또는 부재를 나타냅니다. 예를 들어 메서드에서 String.Compare(String, String, Boolean) 최종 매개 변수 는 ignoreCase
두 문자열의 비교가 대/소문자를 구분하지 않는지(ignoreCase
true
가) 인지 또는 대/소문자를 구분하는지 여부를ignoreCase
나타내는 플래그입니다false
. 그런 다음 조건문에서 플래그 값을 평가할 수 있습니다.
다음 예제에서는 간단한 콘솔 앱을 사용하여 부울 변수를 플래그로 사용하는 방법을 보여 줍니다. 앱은 출력을 지정된 파일(스위치)로 리디렉션하고 출력을 지정된 파일과 콘솔( /f
/b
스위치)로 보낼 수 있도록 하는 명령줄 매개 변수를 허용합니다. 앱은 라는 플래그 isRedirected
를 정의하여 출력을 파일로 보낼지 여부를 나타내고 라는 플래그 isBoth
를 정의하여 출력을 콘솔로 보내야 함을 나타냅니다. F# 예제에서는 재귀 함수를 사용하여 인수를 구문 분석합니다.
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
부울 및 산술 연산
부울 값은 수학 계산을 트리거하는 조건의 존재를 나타내는 데 사용되는 경우도 있습니다. 예를 들어 변수는 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.
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.
부울 및 interop
기본 데이터 형식을 COM으로 마샬링하는 것은 일반적으로 간단 Boolean 하지만 데이터 형식은 예외입니다. 특성을 적용하여 형식을 MarshalAsAttribute 다음 표현으로 마샬링 Boolean 할 수 있습니다.
열거형 형식 | 관리되지 않는 형식 |
---|---|
UnmanagedType.Bool | 0이 아닌 값이 를 나타내고 0이 을 나타내는 true 4바이트 정수 값입니다 false . 이는 구조체의 Boolean 필드와 플랫폼 호출에서 매개 변수의 Boolean 기본 형식입니다. |
UnmanagedType.U1 | 1이 를 나타내고 0이 를 나타내는 true 1 바이트 정수 값입니다 false . |
UnmanagedType.VariantBool | -1이 를 나타내고 0이 를 나타내는 true 2 바이트 정수 값입니다 false . COM interop 호출에서 매개 변수의 Boolean 기본 형식입니다. |
필드
FalseString |
부울 값 |
TrueString |
부울 값 |
메서드
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으로 변환하려고 시도합니다. |
명시적 인터페이스 구현
적용 대상
스레드 보안
이 형식의 모든 멤버는 스레드로부터 안전합니다. instance 상태를 수정하는 것처럼 보이는 멤버는 실제로 새 값으로 초기화된 새 instance 반환합니다. 다른 형식과 마찬가지로 이 형식의 instance 포함된 공유 변수를 읽고 쓰는 것은 스레드 안전을 보장하기 위해 잠금으로 보호되어야 합니다.
피드백
다음에 대한 사용자 의견 제출 및 보기