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

Pal*_*Pal 5 c# compiler-construction nullable operators

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

spot.ViewCount += 1;
Run Code Online (Sandbox Code Playgroud)

仅当ViewCount属性的值为NOT NULL(任何int)时,它才起作用.

为什么编译器会这样做?

我会很感激任何解决方案.

Den*_*nko 8

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

代码:

int? i = null;
i += 1;
Run Code Online (Sandbox Code Playgroud)

实际上是威胁如下:

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;
Run Code Online (Sandbox Code Playgroud)

我使用JustDecompile来获取此代码


key*_*rdP 7

Null是不一样的0.因此,没有逻辑操作会将null增加到int值(或任何其他值类型).例如,如果要将null的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
Run Code Online (Sandbox Code Playgroud)

(虽然记住这没有增加null,但它只是实现了当一个整数被设置为null时为一个可空的int值赋值的效果).

  • 怎么样`myInt = ++ myInt ?? 1` (2认同)