什么是更好的:int.TryParse或尝试{int.Parse()}赶上 [英] What is better: int.TryParse or try { int.Parse() } catch
本文介绍了什么是更好的:int.TryParse或尝试{int.Parse()}赶上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道..我知道......性能不是主要关注的问题在这里,但只是出于好奇,什么是更好的?
布尔解析= int.TryParse(字符串,出NUM);
如果(解析)
...
或
{试
int.Parse(字符串);
}
赶上(){
做某事
}
< DIV CLASS =h2_lin>解决方案
的更好的是非常主观。举例来说,我个人更喜欢 int.TryParse
,因为我经常不关心的为什么的解析失败,如果失败。然而, int.Parse
即可(根据文档)抛出三个不同的异常:
- 输入为空
- 输入是不是一个有效的格式为:
- 输入中包含了许多procudes溢出
如果您关心它为什么失败,那么 int.Parse
显然是更好的选择。
像往常一样,背景为王
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)
...
OR
try {
int.Parse(string);
}
catch () {
do something...
}
解决方案
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:
- the input is null
- the input is not in a valid format
- the input contains a number that procudes an overflow
If you care about why it fails, then int.Parse
is clearly the better choice.
As always, context is king.
这篇关于什么是更好的:int.TryParse或尝试{int.Parse()}赶上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文