如果值为NULL,为什么nullable int(int?)不会通过“+ =”增加值?

时间:2013-07-30 09:36:48

标签: c# compiler-construction operators nullable

我的页面计数器类型是int?:

spot.ViewCount += 1;

仅当ViewCount属性的值为 NOT NULL (任何int)时,它才有效。

为什么编译器会这样做?

我会感激任何解决方案。

4 个答案:

答案 0 :(得分:7)

Null0不同。因此,没有逻辑操作会将null增加到int值(或任何其他值类型)。例如,如果要将可空int的值从null增加到1,则可以执行此操作。

int? myInt = null;
myInt = myInt.HasValue ? myInt += 1 : myInt = 1;

//above can be shortened to the below which uses the null coalescing operator ??
//myInt = ++myInt ?? 1

(虽然记住这不会增加null,但是当它被设置为空时,它只是实现了将整数分配给可空int值的效果。 / p>

答案 1 :(得分:6)

如果您将查看编译器为您生成的内容,那么您将看到背后的内部逻辑。

代码:

int? i = null;
i += 1;

实际上是威胁:

int? nullable;
int? i = null;
int? nullable1 = i;
if (nullable1.HasValue)
{
    nullable = new int?(nullable1.GetValueOrDefault() + 1);
}
else
{
    int? nullable2 = null;
    nullable = nullable2;
}
i = nullable;

我使用JustDecompile来获取此代码

答案 2 :(得分:1)

因为可空类型have lifted operators。一般来说,C#中的it's a specific case of function lifting(或者至少看起来是这样,如果我错了,请纠正我。)

这表示任何null的操作都会产生null结果(例如1 + nullnull * null等)

答案 3 :(得分:-1)

您可以使用这些扩展方法

public static int? Add(this int? num1, int? num2)
{
    return num1.GetValueOrDefault() + num2.GetValueOrDefault();
}

<强>用法:

spot.ViewCount = spot.ViewCount.Add(1);

甚至:

int? num2 = 2; // or null
spot.ViewCount = spot.ViewCount.Add(num2);
相关问题