我想知道两者之间有什么区别,
(int)Something;
int.Parse(Something);
Convert.ToInt32(Something);
我问了我的朋友,没有人帮我解决这个问题。
任何帮助将不胜感激。
谢谢。
我想知道两者之间有什么区别,
(int)Something;
int.Parse(Something);
Convert.ToInt32(Something);
我问了我的朋友,没有人帮我解决这个问题。
任何帮助将不胜感激。
谢谢。
1) 那是一个演员表
2) 解析接收字符串并尝试将其转换为类型。
3) Convert 接受 aobject
作为其参数
一个主要的区别是Convert
不抛出一段ArgumentNullException
时间Parse
。如果它为空,您的演员也会抛出异常。你可以通过使用来解决这个问题
(int?)Something;
你的第一个案例:
(int)Something;
是Explicit cast,所以有些东西是 double/float 等。如果它是一个字符串,你会得到一个错误。
第二种情况:
int.Parse(Something)
int.Parse
以 sting 作为参数,所以Something
必须是字符串类型。
第三种情况:
Convert.ToInt32(Something);
Convert.ToInt32
有许多重载类型为object
,string
等的参数bool
。
Convert.ToInt32(string)
是一个静态包装方法Int32.Parse(string)
。
Convert.ToInt32 的定义如下(来自 ILSpy):
// System.Convert
/// <summary>Converts the specified string representation of a number to an equivalent 32-bit signed integer.</summary>
/// <returns>A 32-bit signed integer that is equivalent to the number in <paramref name="value" />, or 0 (zero) if <paramref name="value" /> is null.</returns>
/// <param name="value">A string that contains the number to convert. </param>
/// <exception cref="T:System.FormatException">
/// <paramref name="value" /> does not consist of an optional sign followed by a sequence of digits (0 through 9). </exception>
/// <exception cref="T:System.OverflowException">
/// <paramref name="value" /> represents a number that is less than <see cref="F:System.Int32.MinValue" /> or greater than <see cref="F:System.Int32.MaxValue" />. </exception>
/// <filterpriority>1</filterpriority>
[__DynamicallyInvokable]
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
没有区别,看MSDN就行了。
使用 ToInt32(String) 方法相当于将值传递给 Int32.Parse(String) 方法。
来源: http: //msdn.microsoft.com/en-us/library/sf1aw27b (v=vs.110).aspx