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