如何将条件运算与可空Int一起使用 [英] How to use Conditional Operation with Nullable Int

查看:72
本文介绍了如何将条件运算与可空Int一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个小问题。有人知道为什么这行不通吗?

A small problem. Any idea guys why this does not work?

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

我试图返回 null 左手表达式为True,否则为 1 。似乎很简单,但是会产生编译错误。

I am trying to return null if the left hand expression is True, else 1. Seems simple but gives compilation error.

由于在 null 之间没有隐式转换,因此无法确定条件表达式的类型。和 int

Type of conditional expression cannot be determined because there is no implicit conversion between null and int.

如果我替换了 null ? null:1 与任何有效的 int ,那么就没有问题。

If I replace the null in ? null : 1 with any valid int, then there is no problem.

推荐答案

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

Yes - the compiler can't find an appropriate type for the conditional expression. Ignore the fact that you're assigning it to an int? - the compiler doesn't use that information. So the expression is:

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

此表达式的类型是什么?语言规范指出,它必须是第二个操作数的类型或第三个操作数的类型。 null 没有类型,因此它必须是 int (第三个操作数的类型)-但是没有从 null int 的转换,因此失败。

What's the type of this expression? The language specification states that it has to be either the type of the second operand or that of the third operand. null has no type, so it would have to be int (the type of the third operand) - but there's no conversion from null to int, so it fails.

将两个操作数中的任何一个都铸造为 int?,它将起作用,或者使用另一种表示空值的方式-因此可以使用以下任何一种方式:

Cast either of the operands to int? and it will work, or use another way of expessing the null value - so any of these:

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

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

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

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

我同意您必须这样做,这有点痛苦。

I agree it's a slight pain that you have to do this.

来自C#3.0语言规范第7.13节:

From the C# 3.0 language specification section 7.13:


The
?的第二和第三操作数:运算符控制
条件表达式的类型。令X和Y为第二个和第三个
操作数的类型的
。然后,

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,


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

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

否则,如果存在从X到Y的隐式转换(§6.1),但不存在从Y到X的
,则Y是类型

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.

否则,如果存在从Y到X的隐式转换(§6.1),但从

不存在X到Y,则X是
条件表达式的类型。

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.

这篇关于如何将条件运算与可空Int一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆