没有隐式 int ->三元语句中的短转换
short s;
s = (EitherTrueOrFalse()) ? 0 : 1;
这失败了:
错误CS0266:无法隐式 将类型“int”转换为“short”。一个 显式转换存在(你是 缺少演员?)
谁能解释为什么会这样?我唯一能想到的是,编译器不会查看第二个值,也不知道两者之间的范围,如果我写了类似
short s;
s = (EitherTrueOrFalse()) ? 0 : 65000;
正确? 唯一的解决方法是使用丑陋的演员阵容?
另外,C# 似乎没有短类型的类型后缀。在我看来,这是一个相当严重的疏忽。不然的话,这倒是一个解决办法……
short s;
s = (EitherTrueOrFalse()) ? 0 : 1;
This fails with:
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?
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器具有从常量表达式到各种基元类型的隐式转换(只要值在适当的范围内),但这里的表达式不是常量 - 它只是一个 int 表达式。 它几乎与: 相同。
就编译器而言,
有两个选项 - 您可以转换整个表达式,或转换后两个操作数中的每一个:
使整个表达式类型为
short
。在这种特殊情况下,遗憾的是没有数字文字后缀来显式声明short
文字。显然语言设计者确实考虑到了这一点,但认为这是一种相对罕见的情况。 (我想我可能会同意。)有关隐式常量转换的部分来自 C# 3.0 规范第 6.1.8 节:
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:
as far as the compiler is concerned.
There are two options - you could cast the whole expression, or cast each of the latter two operands:
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 ashort
literal. Apparently the language designers did consider this, but felt it was a relatively rare situation. (I think I'd probably agree.)The part about implicit constant conversions is from the C# 3.0 spec section 6.1.8:
因为转换是由编译器完成的,而不是在运行时完成,所以我不会称其为丑陋的转换,我会称其为复杂的语法:
我的意思是,这就是它在 C# 中编写的方式,即使看起来很丑。
请参阅此 博客文章。
请参阅 Marc Gravell 对此问题的回答。
Because the cast is done by the compiler, not at runtime, I wouldn't call it an ugly cast, I would call it a complicated syntax:
I mean, this is the way it is written in C#, even if it looks ugly.
See this blog article.
See Marc Gravell's answer on that question.
我想这与无法编译的原因相同:
即每当将short用于某些东西时,它就会被提升为int。
I guess this has the same reason as this won't compile:
I.e. that whenever short is used for something, it gets promoted to int.