[英]Checking for null and set value is not allowed using `?`
Why is setting a value using the new ?
为什么使用新设置值
?
operator for pre-checking of not null is not usable for assignments? 用于预检查非空的运算符不能用于赋值?
For example: 例如:
var list = // ... Some list
var entry = list.FirstOrDefault();
entry?.Value = 123;
This does not compile due to the error: 由于错误,这不会编译:
The left-hand side of an assignment must be a variable, property or indexer.
赋值的左侧必须是变量,属性或索引器。
But calling a method or some thing else works. 但是调用方法或其他东西是有效的。
What is the reason for this compiler behavior? 这种编译器行为的原因是什么?
C# compiler could definitely make this statement work by declaring that once the chain of ?
C#编译器肯定可以通过声明一旦链的
?
s evaluates to null
, all further processing stops. s计算为
null
,所有进一步处理停止。
The problem, however, is what to do when there are side effects on the right: 然而,问题是当右侧有副作用时该怎么办:
entry?.Value = CallSomeFunctionWithSideEffects(123);
Semantics of this is drastically different from other assignments, when the right-hand side is always evaluated. 当总是评估右侧时,这与其他任务的语义完全不同。 Here, however, evaluation of the right-hand side would need to be postponed until the left side is known to produce a non-
null
value. 然而,在这里,需要推迟对右侧的评估,直到已知左侧产生非
null
值。
Function invocation does not suffer from the same problem, because invocation target is processed ahead of parameters: 函数调用不会遇到同样的问题,因为调用目标是在参数之前处理的:
entry?.SetValue(CallSomeFunctionWithSideEffects(123));
Because entry?.Value
might evaluate to null
. 因为
entry?.Value
可能会评估为null
。
Then your code is equivalent to 那么你的代码相当于
null = 123;
which is not valid. 这是无效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.