Convert.ToBoolean (string)和 Boolean. Parse (string)之间的区别是什么?

这两种方法的区别是什么

Convert.ToBoolean()

还有

Boolean.Parse()

有什么理由选择其中一个吗?

此外,是否有任何其他 type.Parse()方法,我应该注意?

谢谢,

马特

54989 次浏览

Boolean.Parse() will convert a string representation of a logical boolean value to a boolean value. Convert.ToBoolean() has multiple overloads that will convert primitive types to their boolean equivalent.

Most, if not all, of the primitive types in C# have an associated *.Parse/Convert.To* method that serve the same purpose as Boolean.Parse()/Convert.ToBoolean().

Convert.ToBoolean(string) actually calls bool.Parse() anyway, so for non-null strings, there's no functional difference. (For null strings, Convert.ToBoolean() returns false, whereas bool.Parse() throws an ArgumentNullException.)

Given that fact, you should use bool.Parse() when you're certain that your input isn't null, since you save yourself one null check.

Convert.ToBoolean() of course has a number of other overloads that allow you to generate a bool from many other built-in types, whereas Parse() is for strings only.

In terms of type.Parse() methods you should look out for, all the built-in numeric types have Parse() as well as TryParse() methods. DateTime has those, as well as the additional ParseExact()/TryParseExact() methods, which allow you specify an expected format for the date.

Here is the short demo:

object ex1 = "True";
Console.WriteLine(Convert.ToBoolean(ex1)); // True
Console.WriteLine(bool.Parse(ex1.ToString())); // True


object ex2 = "true";
Console.WriteLine(Convert.ToBoolean(ex2)); // True
Console.WriteLine(bool.Parse(ex2.ToString())); // True


object ex3 = 1;
Console.WriteLine(Convert.ToBoolean(ex3)); // True
Console.WriteLine(bool.Parse(ex3.ToString())); // Unhandled Exception: System.FormatException


object ex3 = "1";
Console.WriteLine(Convert.ToBoolean(ex3)); // An unhandled exception of type 'System.FormatException' occurred
Console.WriteLine(bool.Parse(ex3.ToString())); // Unhandled Exception: System.FormatException


object ex4 = "False";
Console.WriteLine(Convert.ToBoolean(ex4)); // False
Console.WriteLine(bool.Parse(ex4.ToString())); // False


object ex5 = "false";
Console.WriteLine(Convert.ToBoolean(ex5)); // False
Console.WriteLine(bool.Parse(ex5.ToString())); // False


object ex6 = 0;
Console.WriteLine(Convert.ToBoolean(ex6)); // False
Console.WriteLine(bool.Parse(ex6.ToString())); // Unhandled Exception: System.FormatException


object ex7 = null;
Console.WriteLine(Convert.ToBoolean(ex7)); // False
Console.WriteLine(bool.Parse(ex7.ToString())); // Unhandled Exception: System.NullReferenceException

Note: There are also two properties of bool TrueString and FalseString, but be careful, because bool.TrueString != "true", only bool.TrueString == "True"

Console.WriteLine(bool.TrueString); // True
Console.WriteLine(bool.FalseString); // False