Convert.ToDecimal(string)和Decimal.Parse(string)之间的区别

时间:2020-03-06 14:19:38  来源:igfitidea点击:

Convert.ToDecimal(string)Decimal.Parse(string)之间的区别是什么?

在什么情况下,我们会使用另一种情况?

它对性能有什么影响?

在两者之间进行选择时,我还应该考虑哪些其他因素?

解决方案

从bytes.com:

The Convert class is designed to
  convert a wide range of Types, so you
  can convert more types to Decimal than
  you can with Decimal.Parse, which can
  only deal with String. On the other
  hand Decimal.Parse allows you to
  specify a NumberStyle.
  
  Decimal and decimal are aliases and
  are equal.
  
  For Convert.ToDecimal(string),
  Decimal.Parse is called internally.
  
  Morten Wennevik [C# MVP]

由于Decimal.Parse由Convert.ToDecimal在内部调用,因此,如果我们有极高的性能要求,则可能希望坚持使用Decimal.Parse,它将保存堆栈帧。

与原始主题相关的一种常见建议是,一旦我们不确定输入字符串参数是否将是正确的数字格式表示形式,请立即使用TryParse()。

我们可能没有想到的一个因素是Decimal.TryParse方法。如果它们不能将字符串转换为正确的十进制格式,则Convert.ToDecimalParse都将引发异常。 TryParse方法为我们提供了一个不错的输入验证模式。

decimal result;
if (decimal.TryParse("5.0", out result))
   ; // you have a valid decimal to do as you please, no exception.
else
   ; // uh-oh.  error message time!

对于错误检查用户输入,此模式非常好用。

请记住一个重要区别:

如果为Convert.ToDecimal提供了一个null字符串,它将返回0。

如果要解析的字符串为null,则decimal.Parse将抛出ArgumentNullException。