今天在调试接口时,遇到了以下问题:
运行这句 bool IsRoot = Convert.ToBoolean(dt.Rows[i]["IsRoot"].ToString()) ;结果抛出如下错误:该字符串未被识别为有效的布尔值。开始怀疑表里的数据问题,就换成了Convert.ToBoolean(“0”)试了试,还是报错,然后查了下MSDN于是就明白了。
方法的备注:若要成功执行转换,value 参数必须等于 Boolean.TrueString(值为 True 的常量)或 Boolean.FalseString(值为 False 的常量),否则必须为 null。 在对 value 与Boolean.TrueString 和 Boolean.FalseString 进行比较时,该方法忽略大小写以及前导和尾随空白。
1: using System;
2:
3: public class BooleanConversion
4: {
5: public static void Main()
6: {
7: ConvertToBoolean(null);
8: ConvertToBoolean(String.Empty);
9: ConvertToBoolean("true");
10: ConvertToBoolean("TrueString");
11: ConvertToBoolean("False");
12: ConvertToBoolean(" false ");
13: ConvertToBoolean("-1");
14: ConvertToBoolean("0");
15: }
16:
17: private static void ConvertToBoolean(string value)
18: {
19: try
20: {
21: Console.WriteLine("Converted '{0}' to {1}.", value,
22: Convert.ToBoolean(value));
23: }
24: catch (FormatException)
25: {
26: Console.WriteLine("Unable to convert '{0}' to a Boolean.", value);
27: }
28: }
29: }
30: // The example displays the following output to the console:
31: // Converted '' to False.
32: // Unable to convert '' to a Boolean.
33: // Converted 'true' to True.
34: // Unable to convert 'TrueString' to a Boolean.
35: // Converted 'False' to False.
36: // Converted ' false ' to False.
37: // Unable to convert '-1' to a Boolean.
38: // Unable to convert '0' to a Boolean.
该方法对参数只接受等于”True” 和“False”的值,只能换种方法写了。
Convert.ToBoolean (Int32)
说明:如果 value 为非零值,则为 true;否则为 false。
1:
2: int[] numbers = { Int32.MinValue, -201649, -68, 0, 612, 4038907,
3: Int32.MaxValue };
4: bool result;
5:
6: foreach (int number in numbers)
7: {
8: result = Convert.ToBoolean(number);
9: Console.WriteLine("{0,-15:N0} --> {1}", number, result);
10: }
11: // The example displays the following output:
12: // -2,147,483,648 --> True
13: // -201,649 --> True
14: // -68 --> True
15: // 0 --> False
16: // 612 --> True
17: // 4,038,907 --> True
18: // 2,147,483,647 --> True
19:
有些方法自己还是不清楚用法啊,继续努力学习
欢迎扫描此二维码关注web馆公众号
作者:web馆
出处:http://www.cnblogs.com/xiaoyao2011/
欢迎任何形式的转载,但请务必注明出处。