【问题标题】:what is the difference between Convert.ToInt16 or 32 or 64 and Int.Parse? [duplicate]Convert.ToInt16 或 32 或 64 和 Int.Parse 有什么区别? [复制]
【发布时间】:2011-07-10 16:40:54
【问题描述】:

可能重复:
Whats the main difference between int.Parse() and Convert.ToInt32

我想知道两者有什么区别:

Convert.ToInt16 or Convert.ToInt32 or Convert.ToInt64

Int.Parse

他们都在做同样的事情,所以只想知道有什么不同?

【问题讨论】:

标签: c#


【解决方案1】:

Convert.ToIntobject 转换为整数,如果值为 null,则返回 0。

int x = Convert.ToInt32("43"); // x = 43;
int x = Convert.ToInt32(null); // x = 0;
int x = Convert.ToInt32("abc"); // throws FormatException

Parse字符串转换为整数,如果值无法转换则抛出异常

int x = int.Parse("43"); // x = 43;
int x = int.Parse(null); // x throws an ArgumentNullException
int x = int.Parse("abc"); // throws an FormatException

【讨论】:

  • 我尝试了这些示例(使用 .NET 4 和 .NET 3.5),Convert.ToInt32("abc"); 会像int.Parse("abc"); 一样抛出System.FormatException。唯一没有抛出异常的时间是Convert.ToInt32(null);
  • @Joshua Rodgers:非常感谢,我更正了我的答案。
【解决方案2】:

Convert.ToInt32 如果输入字符串为空,则返回 0。 Int32.Parse 会抛出异常。

【讨论】:

    【解决方案3】:
    1. Convert.To(s) 在参数为空时不会抛出异常,但Parse() 会。Convert.To(s) 在参数为空时返回 0。

    2. Int.Parse()Int.TryParse() 只能转换字符串。 Convert.To(s) 可以采用任何实现 IConvertible 的类。因此,Convert.To(s) 可能是 wee bit slower 而不是 Int.Parse(),因为它必须询问它的参数它的类型是什么。

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 1970-01-01
      • 2011-05-03
      • 2014-02-05
      • 2011-07-26
      • 2016-08-24
      • 2011-05-22
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多