试图将字符串的第一个符号转换为int,得到奇怪的值

Kos*_*mos 2 c# string integer

static void Main(string[] args)
{
    string str_val = "8584348,894";
    //int prefix = Convert.ToInt32(str_val[0]); //prefix = 56 O_o
    //int prefix = (int)str_val[0]; //what, again 56? i need 8!
    int prefix = Convert.ToInt32("8"); //at least this works -_-
}
Run Code Online (Sandbox Code Playgroud)

知道如何将第一个符号转换为正确的数值?

Kub*_*tek 11

如果您使用:

Convert.ToInt32(str_val[0]);
Run Code Online (Sandbox Code Playgroud)

那么你实际上是在调用重载:

Convert.ToInt32(char val);
Run Code Online (Sandbox Code Playgroud)

它给出了作为参数传递的Unicode/Ascii字符数.

如果要转换第一个字符,则需要强制它为字符串类型:

Convert.ToInt32(str_val.Substring(0, 1));
Run Code Online (Sandbox Code Playgroud)

这样你就调用了重载:

Convert.ToInt32(string val);
Run Code Online (Sandbox Code Playgroud)

它实际上做你想要的(将字符串值转换为此字符串表示的int值).