【发布时间】:2016-09-02 16:53:38
【问题描述】:
请查看以下代码并帮助我了解我收到编译器错误的原因。
class Program
{
static void Main(string[] args)
{
Sample smpl = GetSampleObjectFromSomeClass();
//Compiler Error -- the left-hand side of an assignment must be a variable property or indexer
smpl?.isExtended = true;
}
}
public class Sample
{
public bool isExtended { get; set; }
}
我是否应该推断空条件仅用于访问属性、变量等而不用于赋值?
注意:我提到了一个类似的帖子(下面的链接),但在我看来,没有进行足够的讨论。Why C# 6.0 doesn't let to set properties of a non-null nullable struct when using Null propagation operator?
编辑: 我期待像
这样的东西If(null!= smpl)
{
smpl.isExtended = true;
}
看来我的预期不对!
【问题讨论】:
-
你的推论是正确的。空条件运算符仅适用于成员访问,不适用于赋值。我倾向于同意编译器应该允许它用于属性分配(但不是字段),因为属性分配实际上被编译为方法调用。编译后的属性分配看起来像:
smpl?.set_isExtended(true);这将是完全有效的代码。 -
@AndrewHanlon:有趣的观察 (+1),但语义和句法很难一起发挥作用。
-
好的,鉴于 cmets,我已经重新打开了。
-
不知道为什么人们会问“你希望它做什么” - 很明显你希望它做什么(从程序员的角度来看):如果它不为空,则进行分配。
-
我的猜测是空条件运算符在 C# 语言中不是有效的左值。投票@jonskeet