此方法用于使用指定的区域性特定格式信息将逻辑值的指定字符串表示形式转换为其等效的布尔值。
句法:
public static bool ToBoolean (string value, IFormatProvider provider);
参数:
- value:这是一个字符串,其中包含TrueString或FalseString的值。
- provider:提供者:提供特定于区域性的格式信息的对象。该参数被忽略。
返回值:如果value等于TrueString ,则此方法返回true;如果value等于FalseString或null ,则此方法返回false 。
异常:如果该值不等于TrueString或FalseString,则此方法将引发FormatException 。
下面的程序说明了Convert.ToBoolean(String,IFormatProvider)方法的用法:
范例1:
// C# program to demonstrate the
// Convert.ToBoolean() Method
using System;
using System.Globalization;
class GFG {
// Main Method
public static void Main()
{
try {
// creating object of CultureInfo
CultureInfo cultures = new CultureInfo("en-US");
// declaring and intializing String array
String[] values = { null, "true",
"False", " false " };
// calling get() Method
Console.WriteLine("Converted bool value "+
"of specified strings: ");
for (int j = 0; j < values.Length; j++) {
get(values[j], cultures);
}
}
catch (FormatException e) {
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
// Defining get() method
public static void get(string s, CultureInfo cultures)
{
// converting string to specified bool
bool val = Convert.ToBoolean(s, cultures);
// display the converted string
Console.Write(" {0}, ", val);
}
}
输出:
Converted bool value of specified strings:
False, True, False, False,
示例2:对于FormatException
// C# program to demonstrate the
// Convert.ToBoolean() Method
using System;
using System.Globalization;
class GFG {
// Main Method
public static void Main()
{
try {
// creating object of CultureInfo
CultureInfo cultures = new CultureInfo("en-US");
// declaring and intializing String array
String[] values = { null, "true",
"False", " false ", "" };
// calling get() Method
Console.WriteLine("Converted bool value"+
" of specified strings: ");
for (int j = 0; j < values.Length; j++) {
get(values[j], cultures);
}
}
catch (FormatException e) {
Console.WriteLine("\n");
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
// Defining get() method
public static void get(string s, CultureInfo cultures)
{
// converting string to specified bool
bool val = Convert.ToBoolean(s, cultures);
// display the converted string
Console.Write(" {0}, ", val);
}
}
输出:
Converted bool value of specified strings:
False, True, False, False,
Exception Thrown: System.FormatException
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.convert.toboolean?view=netframework-4.7.2#System_Convert_ToBoolean_System_String_System_IFormatProvider_