为什么在 C# 中 Parse 可以工作而 Convert 不能?

Bar*_*rta 0 c# integer

我想对每个数字进行平方str并将其连接到pow.

我有这个简单的代码:

string str = "1234";
string pow = "";

foreach(char c in str)
{
   pow += Math.Pow(Convert.ToInt32(c), 2);
}
Run Code Online (Sandbox Code Playgroud)

它应该返回14916- 相反它返回:2401250026012704

但如果我使用int.Parse(c),它会返回正确的数字。

foreach(char c in str)
{
    int i = int.Parse(c.ToString());
    pow += Math.Pow(i, 2);
}
Run Code Online (Sandbox Code Playgroud)

为什么有效ParseConvert无效?

Joh*_*lay 8

来自以下文档Convert.ToInt32(char)

ToInt32(Char)方法返回一个 32 位有符号整数,表示 value 参数的 UTF-16 编码代码单元。

因此,例如, char'1'将转换为整数 value 49,如 UTF-16 编码中所定义: https: //asecuritysite.com/coding/asc2


该示例的另一种方法int.Parse(c.ToString())Char.GetNumericValue

foreach(char c in str)
{
   pow += Math.Pow(char.GetNumericValue(c), 2);
}
Run Code Online (Sandbox Code Playgroud)

这会将 char 转换为该值的等价数字。