运营商'??'不能应用于子类类型的操作数
以下代码给出了 Main 函数第二行标题中的错误。
public class P {}
public class B : P {}
public class A : P {}
void Main()
{
P p = GetA()??GetB();
}
public A GetA()
{
return new A();
}
public B GetB()
{
return new B();
}
像这样对线路进行简单的调整
p = (P)GetA()??GetB();
or
p = GetA()??(P)GetB();
就可以了。
我很好奇为什么编译器不明白两者都是左侧容器的子类并且允许在没有强制转换的情况下进行操作?
The following code gives the error in the title on the second line in the Main function.
public class P {}
public class B : P {}
public class A : P {}
void Main()
{
P p = GetA()??GetB();
}
public A GetA()
{
return new A();
}
public B GetB()
{
return new B();
}
A simple tweak to the line like these
p = (P)GetA()??GetB();
or
p = GetA()??(P)GetB();
works.
I'm curious why the compiler doesn't understand that both are child classes of the left hand side container and allow the operation without the cast?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
左侧参数的类型必须与右侧的类型兼容,反之亦然。换句话说,必须存在从
B
到A
或从A
到B
的隐式转换。在上面,如果存在从
y
到x
的隐式转换,则x
的类型将成为表达式的类型。如果没有从y
到x
的隐式转换,但有从x
到y
的隐式转换,那么y
的类型就成为表达式的类型。如果两个方向都不存在转换,则繁荣;编译错误。从规格来看:The type of the argument on the left hand side must be compatible with the type on the right hand side or vice versa. In other words, there must exist an implicit conversion from
B
toA
or fromA
toB
.In the above, if there is an implicit conversion from
y
tox
then the type ofx
becomes the type of the expression. if there is no implicit conversion fromy
tox
, but there is an implicit conversion fromx
toy
, then the type ofy
becomes the type of the expression. if no conversion exists in either direction, boom; compilation error. From the spec:因为这样就可以允许:
Because then this would be allowed:
运算符的操作数 ??应该是同一类型:
the operands of the operator ?? should be of same type: