共用方式為


Convert.ToBoolean Method (Object)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Converts the value of a specified Object to an equivalent Boolean value.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public Shared Function ToBoolean ( _
    value As Object _
) As Boolean
public static bool ToBoolean(
    Object value
)

Parameters

Return Value

Type: System.Boolean
true or false, which reflects the value returned by invoking the IConvertible.ToBoolean method for the underlying type of value. If value is nulla null reference (Nothing in Visual Basic), the method returns false.

Examples

The following code sample illustrates the use of the ToBoolean method, converting a string value to a Boolean type.

Public Sub ConvertStringBoolean(ByVal stringVal As String)

   Dim boolVal As Boolean = False

   Try
      boolVal = System.Convert.ToBoolean(stringVal)
      If boolVal Then
         outputBlock.Text &= String.Format( _
             "String is equal to System.Boolean.TrueString.") & vbCrLf
      Else
         outputBlock.Text &= String.Format( _
             "String is equal to System.Boolean.FalseString.") & vbCrLf
      End If
   Catch exception As System.FormatException
      outputBlock.Text &= String.Format( _
          "The string must equal System.Boolean.TrueString " + _
          "or System.Boolean.FalseString.") & vbCrLf
   End Try

   ' A conversion from bool to string will always succeed.
   stringVal = System.Convert.ToString(boolVal)
   outputBlock.Text &= String.Format("{0} as a String is {1}", _
                             boolVal, stringVal) & vbCrLf
End Sub
public void ConvertStringBoolean(string stringVal)
{
   bool boolVal = false;

   try
   {
      boolVal = System.Convert.ToBoolean(stringVal);
      if (boolVal)
      {
         outputBlock.Text += String.Format(
            "String was equal to System.Boolean.TrueString.") + "\n";
      }
      else
      {
         outputBlock.Text += String.Format(
            "String was equal to System.Boolean.FalseString.") + "\n";
      }
   }
   catch (System.FormatException)
   {
      outputBlock.Text += String.Format(
         "The string must equal System.Boolean.TrueString " +
         "or System.Boolean.FalseString.") + "\n";
   }

   // A conversion from bool to string will always succeed.
   stringVal = System.Convert.ToString(boolVal);
   outputBlock.Text += String.Format("{0} as a string is {1}",
      boolVal, stringVal) + "\n";
}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.