gpt4 book ai didi

c# - 三元语句中没有隐式 int -> short 转换

转载 作者:行者123 更新时间:2023-11-30 18:16:26 24 4
gpt4 key购买 nike

short s;
s = (EitherTrueOrFalse()) ? 0 : 1;

这失败了:

error CS0266: Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

谁能解释一下为什么会这样?我唯一能想到的是编译器不查看第二个值并且不知道两者之间的范围,在这种情况下我写了类似

short s;
s = (EitherTrueOrFalse()) ? 0 : 65000;

对吗?唯一的解决办法是使用丑陋的 Actor 阵容?

此外,C# 似乎没有短类型的类型后缀。这是 IMO 非常严重的疏忽。否则,那将是一个解决方案......

最佳答案

编译器有一个从常量表达式到各种基本类型的隐式转换(只要值在适当的范围内),但这里的表达式不是常量 - 它只是一个 int表达。它几乎与以下内容相同:

short s;
s = CallSomeMethodReturningInt32();

就编译器而言。

有两种选择 - 您可以转换整个表达式,或转换后两个操作数中的每一个:

short s = (EitherTrueOrFalse()) ? (short) 0 : (short) 1;

使整体表达式类型简短。在这种特殊情况下,遗憾的是没有数字文字后缀来显式声明 short 文字。显然语言设计者确实考虑到了这一点,但认为这是一种相对罕见的情况。 (我想我可能会同意。)

关于隐式常量转换的部分来自 C# 3.0 规范第 6.1.8 节:

6.1.8 Implicit constant expression conversions

An implicit constant expression conversion permits the following conversions:

  • A constant-expression (§7.18) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.
  • A constant-expression of type long can be converted to type ulong, provided the value of the constant-expression is not negative.

关于c# - 三元语句中没有隐式 int -> short 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553144/

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