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
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
