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) 有什么区别?


基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01