c# - 使用条件运算符时控制台将 char 显示为 int ( ? : )

标签 c# console-application

我对下面代码的输出感到惊讶

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

简而言之,没有从intchar的隐式转换,但是从charint,所以结果类型是 int

是有意义的

关于c# - 使用条件运算符时控制台将 char 显示为 int ( ? : ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53112941/

相关文章:

C# SecuGen 加载回指纹图像进行验证

c# - StringBuilder 编码导致 PInvokeStackImbalance 异常

c# - 使用 wsimport 导入 .net webservice 时出错

c# - Entity Framework 代码优先迁移总是尝试创建新数据库

c++ - 从 C++ 控制台应用程序创建可用程序

c++ - 第一次制作了一个跨越几个类的程序,但我在函数调用方面遇到了问题。

c# - 在字典中添加字典的 int 值

c# - 如何使 .net core 3.1 控制台应用程序中的控制台记录器工作

c# - Azure ASP.NET Core POST 400 错误请求 Blazor Webassemble

windows - Ruby 键盘事件处理