Ternary Operator in C#

不打扰是莪最后的温柔 提交于 2021-02-05 06:50:53

问题


Can anyone please explain to me what happens behind the scenes when you use ternary operator? does this line of code:

string str = 1 == 1 ? "abc" : "def";

is generated as a simple if / else statement? Consider the following:

class A
{
}

class B : A
{
}

class C : A
{
}

Now using ternary expression as follows:

A a1 = 1 == 1 ? new B() : new C();

this doesn't even compile with this error:

Type of conditional expression cannot be determined because there is no implicit conversion between 'ConsoleApp1.B' and 'ConsoleApp2.C'

Can anyone shed light on this one?


回答1:


The conditional operator will effectively use the type of the first expression for the second according to whether there is a conversion - and doesn't take into account bases (otherwise it would just always go to object allowing this: ? "hello" : 10).

In this case, the compiler is correct - there is no conversion between the two types. Add a cast, however on the first one - and it'll compile - (A)new B().




回答2:


The type of the conditional operator expression is required to be either the type of the second operand or the type of the third operand. So one of those must be convertible to the other.

In your case, they're not convertible to each other - but both convertible to a third type (A). That isn't considered by the compiler, but you can force it:

A a1 = 1 == 1 ? new B() : (A) new C();

or

A a1 = 1 == 1 ? (A) new B() : new C();

See section 7.14 of the C# 4 spec for more details.




回答3:


An extract from msdn ?Operator

If condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.

Its pretty explicit.

And your error is pretty explicit too, you are trying to assign a B to a C ... But no cast is available, so error ... Pretty simple




回答4:


Its pretty explicit.

And your error is pretty explicit too, you are trying to assign a B to a C ... But no cast is available, so error ... Pretty simple

Not relevant at all.

B and C derives from A.

The expression is:

A a1 = 1 == 1 ? new B() : new C();

Both expressions return type that derives from A

Just the compiler looks at the expressions of the ?: operator, and don't care what is the type of variable a1 (left side of the expression)... The reason for such implementation is very interesting...



来源:https://stackoverflow.com/questions/9600452/ternary-operator-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!