gpt4 book ai didi

c# - 为什么 C# 中条件运算符总是返回 int?

转载 作者:行者123 更新时间:2023-12-03 02:56:02 25 4
gpt4 key购买 nike

Possible Duplicate:
Conditional operator cannot cast implicitly?

使用 conditional operator 编写语句时,如果任一表达式是数值,则它们始终被解释为 int类型。这使得需要进行强制转换来分配 short使用此运算符的变量。

bool isTrue = true;
int intVal = isTrue ? 1 : 2;
short shortVal = isTrue ? 1 : 2; // Compile error: Cannot implicitly convert type 'int' to 'short'.

编译器不应该知道这两个值都是有效的 short值就像典型的赋值语句中一样( short shortVal = 1; )?

最佳答案

这并不是说条件运算符(又名三元运算符)总是返回整数,而是因为您的文字是整数。

不幸的是,C# 似乎没有字节或短整型的文字说明符(不过,它们有长整型的文字说明符)。

关于c# - 为什么 C# 中条件运算符总是返回 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2356618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com