// all the convertions are well, ignoring case by default Convert.ToBoolean("faLse") Convert.ToBoolean("FaLsE"); Convert.ToBoolean("TrUE"); Convert.ToBoolean("tRue"); bool.Parse("tRuee");// but // Convert.ToBoolean("hello"); // fails // bool.Parse("world"); // fails, throw a System.FormatException: // in .net 2.0 bool result; bool convertSuccess = bool.TryParse("true", out result); // convertSuccess = bool.TryParse("hello", out result); // runs well, although fails to convertHope helpful!
bool btest = Convert.ToBoolean(teststrr);
bool btest;
Boolean.TryParse(teststrr, out btest);
bool btest;
Boolean.TryParse(teststrr, out btest);#_#
string strFlag = "False";
bool bResult ;
if(strFlag == "True")
bResult = true;
else
bResult = false;
Convert.ToBoolean("faLse")
Convert.ToBoolean("FaLsE");
Convert.ToBoolean("TrUE");
Convert.ToBoolean("tRue"); bool.Parse("tRuee");// but
// Convert.ToBoolean("hello"); // fails
// bool.Parse("world"); // fails, throw a System.FormatException:
// in .net 2.0
bool result;
bool convertSuccess = bool.TryParse("true", out result); //
convertSuccess = bool.TryParse("hello", out result); // runs well, although fails to convertHope helpful!
Convert.ToBoolean(str);
convert.toBoolean(string)
如何把string类型转换为bool类型
—-----------------------
-------------------------
本来在CTS中string和bool类型是不可以相互转换的
为什么?
因为不仅仅因为一个是值类型,一个是引用类型
更重要是因为两者的存储方式从根本上说就不一致
但为什么有些情况下可以转换呢,比如string为false或FalseTrue等
因为在这种情况下的转换那其实是因为Convert函数在作祟,个人猜测,可能是一种匹配转换,利用反射来将输入的字符串转换为关键字False或true。。来查看下public static bool ToBoolean(string value);这个函数的详细解释
//
// 摘要:
// 将逻辑值的指定 System.String 表示形式转换为它的等效布尔值。
//
// 参数:
// value:
// 包含 System.Boolean.TrueString 或者 System.Boolean.FalseString 的值的 System.String。
//
// 返回结果:
// 如果 value 等于 System.Boolean.TrueString,则为 true;如果 value 等于 System.Boolean.FalseString
// 或null,则为 false。
从中可以看出,能转换的字符串极为有限。
bool b = false
string str = Console.ReadLine();
if(str == "yourtruestr1"||str == "yourtruestr2"||str == "yourtruestr3")
b = true;代表真的处理了就可以了。