一个小问题。大家知道为什么这不起作用吗?
int? nullableIntVal = (this.Policy == null) ? null : 1;
如果左侧表达式为 True,我将尝试返回 null
,否则返回 1
。看似简单但编译出错。
无法确定条件表达式的类型,因为 null
和 int
之间没有隐式转换。
如果我替换 中的
与任何有效的null
呢? null : 1int
,则没有问题。
最佳答案
是 - 编译器无法为条件表达式找到合适的类型。忽略您将其分配给 int?
的事实 - 编译器不使用该信息。所以表达式是:
(this.Policy == null) ? null : 1;
这个表达式的类型是什么?语言规范声明它必须是第二个操作数的类型或第三个操作数的类型。 null
没有类型,所以它必须是 int
(第三个操作数的类型)——但是没有从 null
到 int
,所以它失败了。
将任一操作数转换为 int?
它将起作用,或者使用另一种方式来表达 null 值 - 所以这些中的任何一个:
(this.Policy == null) ? (int?) null : 1;
(this.Policy == null) ? null : (int?) 1;
(this.Policy == null) ? default(int?) : 1;
(this.Policy == null) ? new int?() : 1;
我同意你必须这样做有点痛苦。
来自 C# 3.0 语言规范第 7.13 节:
The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,
If X and Y are the same type, then this is the type of the conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
Otherwise, no expression type can be determined, and a compile-time error occurs.
关于c# - 如何对 Nullable Int 使用条件运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2881364/