C#Console.WriteLine将Char类型打印为Integer [英] C# Console.WriteLine prints a Char type as Integer
问题描述
我不明白为什么将一次打印char数据类型作为char来打印,而将其他时间打印为整数
static void Main(string [] args)
{
char x ='A';
int i = 0;
Console.WriteLine(x); // A
Console.WriteLine(true?x:0); // 65 ???
Console.WriteLine(false?i:x); // 65 ???
Console.ReadLine();
}
我期望输出为 A,A, A
,但上面的输出是 A,65、65
。为什么?
三元/条件运算符?
需要所有以下三个操作数:
- 计算结果为布尔值的表达式
- 返回值的表达式任何类型的
- 返回与#2相同类型的值的表达式
返回值将始终为同一类型;这就是为什么#2和#3必须具有相同类型的原因。
如果第三个操作数与第二个操作数的类型不同,则编译器将查找隐式转换,并在可能的情况下使用它。
所以当您写
var x = flag时? 65:‘A’;
它与
<$ p完全相同$ p>
int x =标志? (int)65:(int)‘A’;
...并且将始终返回 int
。
如果不是这种情况,则不能将?
的结果分配给强类型变量,这将是一个严重的障碍。
此外,您也可以不编写如下内容:
var x =标志65: A; //注意,这是一个字符串,而不是char
...,因为 A转换为整数。
I dont understand why is this printing char data type once as char, other time as integer
static void Main(string[] args)
{
char x = 'A';
int i = 0;
Console.WriteLine(x); // A
Console.WriteLine(true ? x : 0); // 65 ???
Console.WriteLine(false ? i : x); // 65 ???
Console.ReadLine();
}
I would expect output to be A, A, A
but the output of above is A, 65, 65
. Why?
The ternary/conditional operator ?
requires all of the following three operands:
- An expression that evaluates to a boolean
- An expression that returns a value of any type
- An expression that returns a value of the same type as #2
The return value will always be of the same type; that is why #2 and #3 must be the same type.
If the third operand isn't the same type as the second operand, the compiler will look for an implicit cast and use it if possible.
So when you write
var x = flag ? 65 : 'A';
it is exactly the same as
int x = flag ? (int)65 : (int)'A';
...and will always return an int
.
If this were not the case, the result of the ?
could not be assigned to a strongly typed variable, which would be a serious obstacle.
Also, you cannot write something like this:
var x = flag ? 65 : "A"; //Notice it's a string and not a char
...because there is no implicit cast from "A" to integer.
这篇关于C#Console.WriteLine将Char类型打印为Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!