首页 > 解决方案 > 为什么属性赋值不允许使用空条件运算符?

问题描述

我刚刚注意到属性赋值不允许与空条件运算符结合使用。有了方法,这根本不是问题。

我一直认为属性只是setter 方法的语法糖

item?.SetMarker(Marker.Start); // Perfectly fine
item?.Marker = Marker.Start; // Error   CS0131  The left-hand side of an assignment must be a variable, property or indexer

那么为什么一个允许而另一个不允许呢?

我很确定有一个很好的理论理由。怀着变得更聪明的小希望,我只是想知道为什么:)

PS - 我在 TypeScript 中注意到了同样的行为。

标签: c#typescriptlanguage-designnull-conditional-operator

解决方案


In the second line, when item is null, it does not have any Marker, so you are not able to assign any value to it.

On the other hand, In the first line, when item is null, SetMarker method is not even called and in another word you do not try to assign anything.


推荐阅读