为什么我在字符串的索引 + 问号运算符上得到多个数字?

Why do I get multiple digits on an indexing + question mark operator on a string?

当我运行下面的代码

public class Program
{
    public static void Main()
    {
        string s = "480";
        Console.WriteLine(1 == -1 ? 0 : s[1]);
        Console.WriteLine(s[1]);
    }
}

我明白了

56
8

我不明白我是怎么得到56的。

s[1]是char的int值。

问题运算符表示一个从零开始的整数,表示它是一个整数。它将 char 转换为 int。

I don't understand how I get 56.

第一行解释为字符8:

的UTF-16编码
Console.WriteLine(1 == -1 ? 0 : s[1]);

使用条件运算符,您在此处给出 int 0char 之间的选择,因此编译器将后者隐式转换为 int (这给出你 UTF-16 代码)并将其打印到控制台

在第二行你实际上得到了 char 打印的值

Console.WriteLine(s[1]);

这里没有隐式转换。

您的 0 : s[1]s[1] 中的 char 转换为整数。而8在ASCII table中的值是56.

您也想在左侧使用 char(使用单引号):

Console.WriteLine(1 == -1 ? '0' : s[1]);

来自Documentation on the ?: Operator

"Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other."

"The conditional operator is right-associative."

所以你的结果在第一种情况下变成了数字,在第二种情况下变成了字符。