我想知道之间有什么区别,
(int)Something;
int.Parse(Something);
Convert.ToInt32(Something);
我问过我的朋友,没有任何人帮我这个问题。
任何帮助将不胜感激。
感谢。
答案 0 :(得分:8)
1)这是演员
2)解析收集字符串并尝试将其转换为类型。
3)转换接受object
作为其参数
一个主要区别是Convert
在ArgumentNullException
时不会抛出Parse
。如果它为null,你的演员也会抛出异常。您可以使用
(int?)Something;
答案 1 :(得分:4)
你的第一个案例:
(int)Something;
是显式强制转换,所以有些东西是double / float等。如果是字符串,你会收到错误。
第二种情况:
int.Parse(Something)
int.Parse
将sting作为参数,因此Something
必须是字符串类型。
第三种情况:
Convert.ToInt32(Something);
Convert.ToInt32
有许多重载,它带有object
,string
,bool
等类型的参数。
答案 2 :(得分:0)
没有区别,只需阅读MSDN。
使用ToInt32(String)方法相当于将值传递给Int32.Parse(String)方法。
来源:http://msdn.microsoft.com/en-us/library/sf1aw27b(v=vs.110).aspx
答案 3 :(得分:0)
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);
}