我对下面代码的输出感到惊讶
public static void Main(string[] args)
{
char x = 'A';
int i = 0;
Console.WriteLine (true ? x : 0);
Console.WriteLine(false ? i : x);
}
当我在阅读 C# 面试问题时,我看到了这段代码,上面代码的输出是
输出
65
65
我想知道这是怎么发生的。
有人可以解释一下吗?谢谢!
最佳答案
'A'
是一个 char
并且值为 65
然而,对于为什么这会导致一个整数(而不是 char 的字符串表示)有一个技术解释,您可以在 ECMA C# specifications 中找到它。
12.15 条件运算符
The second and third operands, x and y, of the ?: operator control the type of the conditional expression.
- If x has type X and y has type Y then,
- If X and Y are the same type, then this is the type of the conditional expression.
- Otherwise, if an implicit conversion (§11.2) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
- Otherwise, if an implicit enumeration conversion (§11.2.4) exists from X to Y, then Y is the type of the conditional expression.
- Otherwise, if an implicit enumeration conversion (§11.2.4) exists from Y to X, then X is the type of the conditional expression.
- Otherwise, if an implicit conversion (§11.2) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
- Otherwise, no expression type can be determined, and a compile-time error occurs.
- If only one of x and y has a type, and both x and y are implicitly convertible to that type, then that is the type of the conditional expression.
- Otherwise, no expression type can be determined, and a compile-time error occurs
示例
char Y = 'A';
int X = Y;
Y = X; // compiler error
简而言之,没有从int
到char
的隐式转换,但是从char
到int
,所以结果类型是 int
关于c# - 使用条件运算符时控制台将 char 显示为 int ( ? : ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53112941/