Boolean 構造体

定義

ブール値 (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
属性
実装

注釈

インスタンスにはBoolean、 または falseの 2 つの値trueのいずれかを指定できます。

構造体には Boolean 、次のタスクをサポートするメソッドが用意されています。

次のセクションでは、これらのタスクとその他の使用の詳細について説明します。

ブール値の書式設定

Boolean 文字列表現は、値の場合は "True"、値の true 場合は "False" false です。 値の Boolean 文字列表現は、読み取り専用 TrueString フィールドと FalseString フィールドによって定義されます。

ブール値を ToString 文字列に変換するには、 メソッドを使用します。 Boolean 構造体には、パラメーターなしのToString()メソッドと、書式設定を制御するパラメーターをToString(IFormatProvider)含む メソッドの 2 つのToStringオーバーロードが含まれています。 ただし、このパラメーターは無視されるため、2 つのオーバーロードによって同じ文字列が生成されます。 メソッドでは 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 2 つの値しか含めないため、カスタム書式を簡単に追加できます。 他の文字列リテラルが "True" および "False" に置き換わる単純なカスタム書式の場合は、C# の 条件付き演算子 や Visual Basic の If 演算子 など、言語でサポートされている任意の条件付き評価機能を使用できます。 次の例では、この手法を使用して、値を "True" および "False" ではなく "Yes" および "No" として書式設定 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 の変換はサポートされていないため、対応する変換メソッドは例外を InvalidCastException スローします。

整数または浮動小数点数からブール値への変換はすべて、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

Boolean から数値に変換する場合、クラスの変換メソッドは Convert 1 と false 0 に変換trueされます。 ただし、Visual Basic 変換関数 true は、255 (値への Byte 変換の場合) または -1 (他のすべての数値変換の場合) に変換されます。 次の例では、 メソッドを使用Convertして数値に変換し、Visual Basic の例の場合は Visual Basic 言語の独自の変換演算子を使用して、 を数値に変換trueします。

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 文字列をブール値に変換する 2 つの静的解析メソッド と TryParseが含まれています。 ブール値の文字列表現は、 フィールドと フィールドの値 TrueString (それぞれ "True" と "False") の大文字と FalseString 小文字を区別しない値によって定義されます。 言い換えると、正常に解析される文字列は、"True"、"False"、"true"、"false"、または大文字と小文字が混在しています。 "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'
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 でプログラミングを行っていない場合は、数値文字列を数値に変換してからブール型 (Boolean) に変換する必要があります。 次の例は、整数の配列をブール値に変換することによってこれを示しています。

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

ブール値を比較する

ブール値は true または falseであるため、 メソッドを明示的に呼び出す CompareTo 理由はほとんどありません。これは、インスタンスが指定された値より大きいか、より小さいか、または等しいかを示します。 通常、2 つのブール変数を比較するには、 メソッドを Equals 呼び出すか、言語の等値演算子を使用します。

ただし、ブール変数をリテラルブール値または falseと比較する場合は、ブール値trueを評価した結果がブール値であるため、明示的な比較を行う必要はありません。 たとえば、式は次のようになります。

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

and

if (booleanValue) {
if booleanValue then
If booleanValue Then

は同等ですが、2 つ目はよりコンパクトです。 ただし、どちらの手法も同等のパフォーマンスを提供します。

バイナリ値としてブール値を使用する

次の 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) 呼び出します。 メソッドは、1 つの要素を持つバイト配列を返します。 バイナリ表現からブール値を復元するには、 メソッドを 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

ブール値を使用して操作を実行する

このセクションでは、アプリでブール値を使用する方法について説明します。 最初のセクションでは、フラグとしての使用について説明します。 2 つ目は、算術演算での使用を示しています。

フラグとしてのブール値

ブール変数は、何らかの条件の有無を示すために、フラグとして最も一般的に使用されます。 たとえば、 メソッドの String.Compare(String, String, Boolean) 最後のパラメーター である は、 ignoreCase2 つの文字列の比較で大文字と小文字が区別されない (ignoreCase が ) か、大文字と小文字が true区別されるかを示すフラグです (ignoreCasefalse)。 その後、フラグの値を条件付きステートメントで評価できます。

次の例では、単純なコンソール アプリを使用して、ブール変数をフラグとして使用する方法を示します。 アプリは、出力を指定されたファイル (スイッチ) にリダイレクトし、出力を指定されたファイルとコンソール ( /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.

ブール値と相互運用

基本データ型を COM にマーシャリングするのは一般的に簡単ですが、 Boolean データ型は例外です。 属性を MarshalAsAttribute 適用して、次のいずれかの表現に型をマーシャリング Boolean できます。

列挙型 アンマネージド形式
UnmanagedType.Bool 4 バイトの整数値。0 以外の値は を表 true し、0 は を表します false。 これは、構造体内の Boolean フィールドとプラットフォーム呼び出しのパラメーターの既定の Boolean 形式です。
UnmanagedType.U1 1 バイトの整数値。1 は を true 表し、0 は を表します false
UnmanagedType.VariantBool 2 バイトの整数値。-1 は を true 表し、0 は を表します false。 これは、COM 相互運用機能呼び出し Boolean のパラメーターの既定の形式です。

フィールド

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)

現在のブール型インスタンスの値を、指定した文字スパンに書式設定しようとします。

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 がスローされます。

IConvertible.ToDateTime(IFormatProvider)

この変換はサポートされていません。 このメソッドを使用しようとすると、InvalidCastException がスローされます。

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)」をご覧ください。

IParsable<Boolean>.Parse(String, IFormatProvider)

文字列を値に解析します。

IParsable<Boolean>.TryParse(String, IFormatProvider, Boolean)

ブール値 (true または false) を表します。

ISpanParsable<Boolean>.Parse(ReadOnlySpan<Char>, IFormatProvider)

文字のスパンを値に解析します。

ISpanParsable<Boolean>.TryParse(ReadOnlySpan<Char>, IFormatProvider, Boolean)

ブール値 (true または false) を表します。

適用対象

スレッド セーフ

この型のすべてのメンバーはスレッド セーフです。 インスタンスの状態を変更するように見えるメンバーは、実際には新しい値で初期化された新しいインスタンスを返します。 他の型と同様に、この型のインスタンスを含む共有変数の読み取りと書き込みは、スレッドセーフを保証するためにロックによって保護する必要があります。