gpt4 book ai didi

c# - 如何对 Nullable Int 使用条件运算

转载 作者:太空狗 更新时间:2023-10-29 18:02:51 24 4
gpt4 key购买 nike

一个小问题。大家知道为什么这不起作用吗?

int? nullableIntVal = (this.Policy == null) ? null : 1;

如果左侧表达式为 True,我将尝试返回 null,否则返回 1。看似简单但编译出错。

无法确定条件表达式的类型,因为 nullint 之间没有隐式转换。

如果我替换 中的 null 呢? null : 1 与任何有效的int,则没有问题。

最佳答案

是 - 编译器无法为条件表达式找到合适的类型。忽略您将其分配给 int? 的事实 - 编译器不使用该信息。所以表达式是:

(this.Policy == null) ? null : 1;

这个表达式的类型是什么?语言规范声明它必须是第二个操作数的类型或第三个操作数的类型。 null 没有类型,所以它必须是 int(第三个操作数的类型)——但是没有从 nullint,所以它失败了。

将任一操作数转换为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com