我正在做一些编码面试练习题,我不知道为什么这个问题的答案是 65, 65

I'm doing some coding interview practice questions and I don't know why the answer to this problem is 65, 65

public class Program
    {      
      public static void Main(string[] args)
        {
          char x = 'A';
           int i = 0;
          Console.WriteLine (true  ? x : 0);
          Console.WriteLine(false ? i : x); 
        }
    }

我在 google 上找不到任何东西,有人请解释为什么输出是 65,65

因为 char 只不过是一个数字,更准确地说是一个带符号的 int,如文档所示:

The char type is implicitly convertible to the following integral types: ushort, int, uint, long, and ulong

字符 'A' 具有 unicode 代码点 65。因此你的三元只是 returns int,在你的情况下 65.

在 MSDN 上查看有关 char 的更多信息:https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/char

A在ASCII编码中是65。三元运算符本质上是输出 A 的 char 值,在本例中为 65。

三元运算符本质上是一个if else语句。所以 Console.WriteLine (true ? x : 0); 将输出 65,因为 x 在三元的真实部分。 Console.WriteLine(false ? i : x); 也将输出 65,因为 x 在三进制的假(else)部分

因为您可以将 char 隐式转换为 int 而不是其他方式,所以 int 类型获胜并设置结果的类型。

如果是相反的结果,您会得到 'A'。

详情).

        int intVar = '1';       //ok
        char charVar = (char)1; //ok
        char charVarError = 1;  //error