c# - 为什么属性赋值不允许使用空条件运算符?
问题描述
我刚刚注意到属性赋值不允许与空条件运算符结合使用。有了方法,这根本不是问题。
我一直认为属性只是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 中注意到了同样的行为。
解决方案
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.
推荐阅读
- javascript - Basic MDCSelect not displaying correctly
- javascript - CSS Span 标签导致换行 - 使用网格布局时
- r - Error unnesting list-columns in R even all have equal lengths
- r - 总是重新安装包
- javascript - Animated number counter not showing decimal numbers
- jquery - Access denied exception with jquery Ajax call when origin is ms-local-stream
- javascript - 更改输入图标并删除以前的图标(Jquery)
- angularjs - 在角度输入中拆分网关和掩码
- git - 提交时更新 Lambda 函数
- laravel - Laravel 中未定义路由 [admin/CountryController.store]