请考虑以下代码:
null
它将tt
分配给?.
。
问题是:为什么它能正常运作?
我认为必须先使用?.Where(...)
,然后选择null
返回IEnumerable<int> xx = null;
var yy = xx?.Where(x => x > 2);
var zz = yy.Select(x => x.ToString());
。
此外,如果我将第二行分成两行:
ArgumentNullException
第三行的yy == null
为 function stop-adobe {
param ([string]$computername)
Invoke-Command $computername -scriptblock {
#tests to see if the window is open and returns a value of true or false
$test = Get-Process | where {$_.MainWindowTitle} | where {$_.ProcessName -like "*acro*"}
If ($test) {
msg * "Adobe is running perfectly, please inform the person you are on the phone with of this so that we can further troubleshoot"
}
else {
#kills the process since it does not have an active window
Stop-Process -Id $test.Id
}
}
。
有什么神奇之处? :)
如果这是因为短路,我从未想过它会像这样。
答案 0 :(得分:3)
空条件运算符或者也称为空传播运算符是短路,即如果链中的一个操作:< / p>
var tt = xx?.Where(x => x > 2).Select(x => x.ToString());
返回null
,然后链的其余部分停止执行。
因此,在上面的示例中,Where
永远不会被调用,因为xx
是null
。
至于第二个例子,你得到一个ArgumentNullException
因为这是扩展方法的行为。在这种特定情况下,当{em>源或提供的选择器为Select
时,ArgumentNullException
会引发null
。
答案 1 :(得分:2)
是的,这是由于短路造成的。来自MSDN reference:
... [T]零条件运算符是短路的。如果条件成员访问和索引操作链中的一个操作返回null,则链的其余部分将停止执行。
第二个示例抛出的原因是因为您有单独的unchained语句。短路不能应用于多个语句。