What is better: int.TryParse or try { int.Parse() } catch (更好的是: int.TryParse 或 try { int.Parse() } catch)
问题描述
我知道..我知道...性能不是这里的主要关注点,只是出于好奇,什么更好?
I know.. I know... Performance is not the main concern here, but just for curiosity, what is better?
bool parsed = int.TryParse(string, out num);
if (parsed)
...
或
try {
int.Parse(string);
}
catch () {
do something...
}
推荐答案
Better 是非常主观的.例如,我个人更喜欢int.TryParse,因为我通常不关心为什么解析失败,如果它失败了.但是,int.Parse 可以(根据 documentation) 抛出三个不同的异常:
Better is highly subjective. For instance, I personally prefer int.TryParse, since I most often don't care why the parsing fails, if it fails. However, int.Parse can (according to the documentation) throw three different exceptions:
- 输入为空
- 输入的格式无效
- 输入包含一个会产生溢出的数字
如果您关心它失败的原因,那么 int.Parse 显然是更好的选择.
If you care about why it fails, then int.Parse is clearly the better choice.
一如既往,语境为王.
这篇关于更好的是: int.TryParse 或 try { int.Parse() } catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:更好的是: int.TryParse 或 try { int.Parse() } catch
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
