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) 有什么区别?
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30