本文介绍了在三元条件语句中更改动态类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,类型 dynamic 允许您在运行时更改变量的类型,例如:

In C#, the type dynamic allows you to change a variable's type at runtime, for example:

dynamic x = "foo";
x = 42;

另一个例子:

dynamic x;
if (true)
    x = "foo";
else
    x = 42;

但是,当使用速记?:"三元条件语句时,

However, when using the shorthand "?:" ternary conditional statement,

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

无法编译:

错误CS0173:无法确定条件表达式的类型,因为在'string'和'int'之间没有隐式转换

error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'int'

为什么会这样?

推荐答案

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

The specification has this to say about how it uses the operands to determine the type of a ternary 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;

这篇关于在三元条件语句中更改动态类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:13