eni*_*_0z 3 powershell powershell-5.0
我有一个函数(实际上是这个函数的多个实例),但有时它可能返回多个元素的列表,有时它可能返回单个元素。我希望该函数每次都返回一个数组 ( [System.Object[]]),以便(在接收端)我始终可以预期它是一个数组并对其进行索引,即使我只是拉取第 0 个元素。
我尝试过以多种方式转换返回类型(参见下面的代码)...包括(例如)return @("asdf")和return [System.Object[]]@("asdf")类似的,但似乎唯一获得一致行为的方法是在数组中添加第二个空元素.. ..这对我来说感觉不对。(见下面的代码)
function fn1 {
return @("asdf")
}
function fn2 {
return [array]@("asdf")
}
function fn3 {
return [System.Object[]]@("asdf")
}
function fn4 {
# This works but with the side effect of sending a null string that is not actually necessary
return @("asdf",$Null)
}
$v = fn1 # Same for fn2, fn3.
$v.GetType().Name # Expected: Object[], Actual: String
$v[0] # Expected: "asdf", Actual: "a"
$v = fn4
$v.GetType().Name # Expected: Object[], Actual: Object[]
$v[0] # Expected: "asdf", Actual: "asdf"
Run Code Online (Sandbox Code Playgroud)
作为包装额外数组的替代方法,请使用Write-Output -NoEnumerate:
function fn1 {
Write-Output @('asdf') -NoEnumerate
}
Run Code Online (Sandbox Code Playgroud)
或者,在 4.0 版本之前的 cmdlet 绑定/高级函数中:
function fn1 {
[CmdletBinding()]
param()
$PSCmdlet.WriteObject(@('asdf'), $false)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
287 次 |
| 最近记录: |