C#中Convert和Parse的区别是什么?

3

我想知道以下几点之间的区别:

(int)Something;

int.Parse(Something);

Convert.ToInt32(Something);

我向朋友们询问了这个问题,但没有人能够帮助我。

非常感谢您的帮助。

谢谢。


6
因为在谷歌上搜索太过普遍。 - Soner Gönül
因为 Stack Overflow 是开发者的谷歌。 - Abbas
看一下框架的源代码...比向朋友询问更有教育意义。 - Will Dean
@Abbas,因为它是唯一一个有答案的网站吗? - Silvermind
4个回答

9

1) 那是一个转换。

2) 解析将一个字符串作为输入,并尝试将其转换为一种类型。

3) Convert 接受一个 object 作为其参数。

一个主要的区别是,Convert 不会抛出 ArgumentNullException 异常,而 Parse 会。如果它为空,您的转换也会引发异常。您可以通过使用以下方式避免:

(int?)Something;

4

您的第一个案例:

(int)Something;
显式转换是指将某些内容转换为double/float等数据类型。如果它是一个字符串,你会得到一个错误。
第二种情况:
int.Parse(Something)

int.Parse 接受字符串作为参数,所以 Something 必须是字符串类型。

第三种情况:

Convert.ToInt32(Something);

Convert.ToInt32 有很多重载版本,可以接受 objectstringbool 等类型的参数。


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);
}

有一个注意点:Convert.ToInt32 接受空参数时,会返回默认值(即0)。 - dcastro

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接