作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我注意到编写PowerShell类行有趣而又奇怪的事情:
class A {
[object] WhereObject(){
return @(1,2) | Where-Object {$_ -gt 2}
}
[object] Where(){
return @(1,2).Where( {$_ -gt 2})
}
}
$a = new-object A
$a.WhereObject() # Throw exception Index was out of range. Must be non-negative and less than the size of the collection.
$a.Where() # Works well
function Get-NullIfEmpty {
param(
[Parameter(ValueFromPipeline=$true)][array] $CollectionOrEmtpy
)
begin { $output = $null }
process
{
if($output -eq $null -and $CollectionOrEmtpy -ne $null){
$output = @()
}
foreach ($element in $CollectionOrEmtpy)
{
$output += $element
}
}
end { return $output }
}
[object] WhereObject() {
return @(1,2) | Where-Object {$_ -gt 2} | Get-NullIfEmpty
}
最佳答案
.Where()
方法(在表达式模式下评估),始终返回[System.Collections.ObjectModel.Collection[psobject]]
实例:.Count
属性返回0
)。 Where-Object
cmdlet 使用管道语义,这意味着以下输出行为:[System.Management.Automation.Internal.AutomationNull]::Value
单例。[object[]]
数组中。AutomationNull
)现在被强制为$null
;看到原始的bug report on GitHub。 [List[object]]
实例用于收集通过内部管道执行的方法调用的输出。如果该内部管道输出“无”(即[System.Management.Automation.Internal.AutomationNull]::Value
),则不会将任何对象添加到列表中。但是,后续代码假定列表中至少有一个对象,并且盲目访问索引0
,从而导致手头的错误。class A {
# Try to return [System.Management.Automation.Internal.AutomationNull]::Value
# (which is what `& {}` produces).
[object] WhereObject(){ return & {} }
}
$a = new-object A
$a.WhereObject() # Throw exception Index was out of range. Must be non-negative and less than the size of the collection.
至于所需的行为:$null
获取输出。
关于PowerShell Where对象与Where方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50956909/
我是一名优秀的程序员,十分优秀!