没有隐式int - >三元声明总之转换 [英] No implicit int -> short conversion in ternary statement

查看:192
本文介绍了没有隐式int - >三元声明总之转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这失败:

错误CS0266:无法隐
  转换类型'诠释'到'短'。一个
  显式转换存在(是你
  缺少强制转换?)

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

谁能解释这是为什么?我能想到的唯一的事情就是编译器不会再看第二值,不知道这两者之间的范围内,我写了类似的情况。

Can anyone explain why this is so? The only thing I can think of is that the compiler doesn't look at the second value and doesn't know the range between the two, in the case I wrote something like

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

正确?
唯一的解决方法是用一个丑陋的投?

Correct? The only fix is with an ugly cast?

此外,似乎C#不具有用于短类型的类型后缀。这是一个pretty坟墓监督海事组织。否则,将一直在一个解决方案...

Also, it seems C# does not have a type suffix for the short type. That's a pretty grave oversight IMO. Otherwise, that would've been a solution...

推荐答案

编译器有从的的前pression各种基本类型的隐式转换(只要该值范围内适当的范围内),但这里的前pression不是恒定的 - 它只是一个int前pression。这是pretty一样一样的:

The compiler has an implicit conversion from a constant expression to various primitive types (so long as the value is within the appropriate range), but here the expression isn't constant - it's just an int expression. It's pretty much the same as:

short s;
s = CallSomeMethodReturningInt32();

至于编译器而言。

as far as the compiler is concerned.

有两种选择 - 你可以施放整个前pression,或每次投后两个操作数:

There are two options - you could cast the whole expression, or cast each of the latter two operands:

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

使整个前pression键入。在这种特殊情况下,这是一个遗憾的是,没有一个数字文字后缀以显式声明文字。显然,语言的设计者确实考虑这一点,但觉得这是一个比较罕见的情况。 (我想我可能会同意。)

to make the overall expression type short. In this particular case, it's a pity that there isn't a numeric literal suffix to explicitly declare a short literal. Apparently the language designers did consider this, but felt it was a relatively rare situation. (I think I'd probably agree.)

有关隐式转换不变的部分是从C#3.0规范6.1.8节:

The part about implicit constant conversions is from the C# 3.0 spec section 6.1.8:

6.1.8隐定前pression转换

这是隐定
  前pression转换允许的
  下列转换:

An implicit constant expression conversion permits the following conversions:


      
  • A 恒前pression 的(§7.18)型
       INT 可转换为类型为sbyte,
      字节 USHORT UINT ULONG
      所提供的价值
      的恒前pression 的距离
      在目标类型的范围。

  •   
  • 系统
      的恒前pression 的类型 CAN
      被转换成键入 ULONG ,提供
      的值的恒前pression
      是不是消极的。

  •   
  • 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.

这篇关于没有隐式int - >三元声明总之转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆