System.Convert.ToBoolean 方法 (String)

方法描述

将逻辑值的指定字符串表示形式转换为其等效的布尔值。

语法定义(C# System.Convert.ToBoolean 方法 (String) 的用法)

public static bool ToBoolean(
	string value
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
value System-String 包含 Boolean.TrueString 或 Boolean.FalseString 值的字符串。
返回值 System.Boolean 如果 value 等于 TrueString,则为 true;如果 value 等于 FalseString 或 null,则为 false。

提示和注释

若要成功执行转换,value 参数必须等于 Boolean.TrueString(值为 True 的常量)或 Boolean.FalseString(值为 False 的常量),否则必须为 null。 在对 value 与 Boolean.TrueString 和 Boolean.FalseString 进行比较时,该方法忽略大小写以及前导和尾随空白。

如果您希望在转换失败时不处理异常,则可以转而调用 Boolean.TryParse 方法。 它将返回 Boolean 值,该值指示转换是否成功。

System.Convert.ToBoolean 方法 (String)例子

下面的示例使用 Convert.ToBoolean(String) 方法将不同的字符串转换为布尔值。

using System;

public class BooleanConversion
{
   public static void Main()
   {
      ConvertToBoolean(null);
      ConvertToBoolean(String.Empty);
      ConvertToBoolean("true");
      ConvertToBoolean("TrueString");
      ConvertToBoolean("False");
      ConvertToBoolean("    false    ");
      ConvertToBoolean("-1");
      ConvertToBoolean("0");
   }

   private static void ConvertToBoolean(string value)
   {
      try
      {
         Console.WriteLine("Converted '{0}' to {1}.", value,  
                           Convert.ToBoolean(value));
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to convert '{0}' to a Boolean.", value);
      }
   }
}
// The example displays the following output to the console:
//       Converted '' to False.
//       Unable to convert '' to a Boolean.
//       Converted 'true' to True.
//       Unable to convert 'TrueString' to a Boolean.
//       Converted 'False' to False.
//       Converted '    false    ' to False.
//       Unable to convert '-1' to a Boolean.
//       Unable to convert '0' to a Boolean.

异常

异常 异常描述
FormatException value 不等于 TrueString 或 FalseString。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。