TryCatch与TryParse的优缺点 [英] pros and cons of TryCatch versus TryParse
本文介绍了TryCatch与TryParse的优缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用以下两种方法中的一种来从对象中拉出双精度的利弊是什么?除了个人喜好以外,我正在寻找反馈的问题还包括调试的简易性,性能,可维护性等.
What are the pros and cons of using either of the following approaches to pulling out a double from an object? Beyond just personal preferences, issues I'm looking for feedback on include ease of debugging, performance, maintainability etc.
public static double GetDouble(object input, double defaultVal)
{
try
{
return Convert.ToDouble(input);
}
catch
{
return defaultVal;
}
}
public static double GetDouble(object input, double defaultVal)
{
double returnVal;
if (double.TryParse(input.ToString(), out returnVal))
{
return returnVal;
}
else
{
return defaultVal;
}
}
推荐答案
-
TryParse
将比捕获异常更快 -
TryParse
表示预期-这里没有发生任何异常情况,只是您怀疑您的数据可能无效. -
TryParse
不在正常控制流中使用异常处理 TryParse
will be faster than catching an exceptionTryParse
indicates something expected - nothing exceptional is happening here, it's just that you suspect your data may not be valid.TryParse
isn't using exception handling for normal control flow
基本上,请使用TryParse
:)
顺便说一下,您的代码可以重写为:
By the way, your code can be rewritten as:
public static double GetDouble(object input, double defaultVal)
{
double parsed;
return double.TryParse(input.ToString(), out parsed)) ? parsed : defaultVal;
}
这篇关于TryCatch与TryParse的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文