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 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) 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Convert.ToBoolean(string) 和 Boolean.Parse(string) 有什么区别?
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
