我有一个 int 类型的页面计数器?:
spot.ViewCount += 1;
仅当 ViewCount 属性的值为NOT NULL(任何整数)时才有效。
编译器为什么这样做?
如果有任何解决方案,我将不胜感激。
Null
与 0
不同。因此,不存在将 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值,当它被设置为null时的效果)。
如果您查看编译器为您生成了什么,那么您将看到背后的内部逻辑。
代码:
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 得到这段代码
因为可空类型 已经提升了运算符。通常,这是 C# 中函数提升的特定情况(或者至少看起来是这样,如果我错了请纠正我)。
这意味着任何带有
null
的操作都会有一个null
的结果(例如1 + null
,null * null
等)
您可以使用这些扩展方法:
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);