对“var”的质疑关键字和三元运算符 ?:
如果 var
关键字在编译时解析,下面的代码如何工作?
class A {
}
class B : A {
}
int k = 1;
var x = (k < 0) ? new B() : new A();
编辑:
我终于明白问题不在于 var 本身,而在于 ?: 运算符的行为。出于某种原因,我认为以下情况是可能的:
object x = some ? 1 : ""
这根本不可能:)
相关问题(关于三元运算符):
为什么在三元运算符中分配 null失败:null 和 int 之间没有隐式转换?
If var
keyword is resolved at compile time, how does the following work?
class A {
}
class B : A {
}
int k = 1;
var x = (k < 0) ? new B() : new A();
Edit:
I finally understood that the problem is not about the var
itself, but about the behaviour of the ?:
operator. For some reason, I thought that the following could be possible:
object x = something ? 1 : ""
and that's not possible at all :)
Related question (about ternary operator):
Why assigning null in ternary operator fails: no implicit conversion between null and int?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
结果是
A
类型,因为两个变量都是A
类型,并且至少其中一个直接是类型>A
(不通过某种转换)。编译器会检查三元表达式的两个部分,如果其中一个是另一个的子类型,则整个表达式将成为更通用的超类型。
但是,如果两者都不是直接的常见类型,则会发生编译器错误,可能是因为它不知道要为您向上转换多少(并且感觉不想找出)。
请参阅此处:
The result is of type
A
, because both of the variables are of typeA
, and at least one of them is directly of typeA
(not through some conversion).The compiler takes a look at both parts of the ternary expression, and if one of them is a subtype of the other, the entire expression becomes the more general supertype.
However, if neither is directly of the common type, then a compiler error occurs, probably because it doesn't know how much to upcast for you (and it doesn't feel like finding out).
See here:
结果是
A
。确认它的一个简单方法是将鼠标放在var
上。The result is
A
. An easy way to confirm it is to place your mouse over thevar
.我还没有测试过这种退化的情况。但我敢打赌要么(1)编译器抱怨要么(2)'x'是'A'类型。
I haven't tested this degenerate case. But I would bet either (1) compiler complains or (2) 'x' is of type 'A'.