What is the difference between Convert.ToBoolean(string) and Boolean.Parse(string)?(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 string
s,没有功能上的区别.(对于 null string
s,Convert.ToBoolean()
返回 false
,而 bool.Parse()
抛出ArgumentNullException
.)
Convert.ToBoolean(string)
actually calls bool.Parse()
anyway, so for non-null string
s, there's no functional difference. (For null string
s, 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 string
s 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) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Convert.ToBoolean(string) 和 Boolean.Parse(string) 有什么区别?


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01