且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在三元条件语句中更改动态类型

更新时间:2022-01-21 02:13:52

该规范说明了如何使用操作数确定三元表达式的类型:

The specification has this to say about how it uses the operands to determine the type of a ternary expression:

?:运算符的第二和第三操作数x和y控制条件表达式的类型.

The second and third operands, x and y, of the ?: operator control the type of the conditional expression.

•如果x的类型为X,y的类型为Y,

•If x has type X and y has type Y then,

o如果X和Y是同一类型,则这是条件表达式的类型.

o If X and Y are the same type, then this is the type of the conditional expression.

o否则,如果存在从X到Y的隐式转换(第11.2节),但不存在从Y到X的隐式转换,则Y是条件表达式的类型.

o Otherwise, if an implicit conversion (§11.2) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

o否则,如果存在从X到Y的隐式枚举转换(第11.2.4节),则Y是条件表达式的类型.

o Otherwise, if an implicit enumeration conversion (§11.2.4) exists from X to Y, then Y is the type of the conditional expression.

o否则,如果存在从Y到X的隐式枚举转换(第11.2.4节),则X是条件表达式的类型.

o Otherwise, if an implicit enumeration conversion (§11.2.4) exists from Y to X, then X is the type of the conditional expression.

o否则,如果存在从Y到X的隐式转换(第11.2节),但不存在从X到Y的转换,则X是条件表达式的类型.

o Otherwise, if an implicit conversion (§11.2) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

o否则,将无法确定表达式类型,并且会发生编译时错误.

o Otherwise, no expression type can be determined, and a compile-time error occurs.

显然,对于 string int ,这些(除最后一条语句外)都不适用,因此会出现编译时错误.

Obviously none of these (excluding the final statement) are true for string and int, so you get the compile time error.

从本质上讲,您要向其分配三元结果的变量的类型不会对三元表达式的结果类型产生影响.如果要返回动态,则需要将其中一个操作数直接转换为动态,如下所示:

Essentially, the type of the variable you're assigning the result of your ternary to doesn't have an impact on the resulting type of the ternary expression. If you want to return dynamic, you'll need to cast one of the operands to dynamic directly, like so:

dynamic x = (true) ? (dynamic) "foo" : 42;