更好的是: int.TryParse 或 try { int.Parse() } catch [英] What is better: int.TryParse or try { int.Parse() } catch

查看:26
本文介绍了更好的是: 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆