Convert.ToBoolean(string) 和 Boolean.Parse(string) 有什么区别? [英] What is the difference between Convert.ToBoolean(string) and Boolean.Parse(string)?

查看:23
本文介绍了Convert.ToBoolean(string) 和 Boolean.Parse(string) 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法有什么区别

Convert.ToBoolean()

Boolean.Parse()?

有什么理由使用其中一个吗?

Is there any reason to use one or the other?

此外,还有其他我应该注意的 type.Parse() 方法吗?

Additionally, are there any other type.Parse() methods that I should watch out for?

谢谢,

马特

推荐答案

Convert.ToBoolean(string) 实际上调用 bool.Parse() 无论如何,所以对于非null strings,没有功能上的区别.(对于 null strings,Convert.ToBoolean() 返回 false,而 bool.Parse() 抛出ArgumentNullException.)

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.)

鉴于这一事实,当您确定您的输入不为空时,您应该使用 bool.Parse(),因为您为自己节省了一次空检查.

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() 当然还有许多其他重载,允许您从许多其他内置类型生成 bool,而 Parse() 仅适用于 string.

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.

就你应该注意的 type.Parse() 方法而言,所有内置数字类型都有 Parse() 以及 TryParse() 方法.DateTime 具有这些以及附加的 ParseExact()/TryParseExact() 方法,它们允许您指定日期的预期格式.

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.

这篇关于Convert.ToBoolean(string) 和 Boolean.Parse(string) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆