如何强制函数返回单个元素数组而不是包含的对象?

问题描述 投票:0回答:3

我有一个函数(实际上是这个函数的多个实例),但有时它可能返回多个元素的列表,有时它可能返回单个元素。 我希望函数每次都返回一个数组 (

[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" 
powershell powershell-5.0
3个回答
5
投票

作为包装额外数组的替代方法,请使用

Write-Output -NoEnumerate
:

function fn1 {
  Write-Output @('asdf') -NoEnumerate
}

或者,在 4.0 版本之前的 cmdlet 绑定/高级功能中:

function fn1 {
  [CmdletBinding()]
  param()

  $PSCmdlet.WriteObject(@('asdf'), $false)
}

3
投票

如果我理解你的问题,你可以在返回值时使用

,
运算符;例如:

function fn1 {
  ,@("asdf")
}

该函数将输出一个单元素数组。


0
投票

` <# You can create the function, call the array results and then store them in the array again using a foreach-object loop. Such as: #>

<# not sure it is nessesary but is always a good practice to declare the array outside the function. #>

函数 make-Array { 参数( $东西 ) <# some code here, param is optional #>

$some_array = @(时间1,项目2,项目3)

<# make sure to call the array here, this will print out all the contents of the array. #> $一些_数组

返回#将此留空 }

<# This is where you can get the array stored. #>

创建数组 $data | Foreach-object {some_array += $_}

<# This will now take each deserialized output from the array in the function and then add them back again to the array, or anything else you'd like. Sicne the arrya is already global you do not need to pass it as an argument to the function nor do you need to declare it inside the funciton. #>`

© www.soinside.com 2019 - 2024. All rights reserved.