小编eni*_*_0z的帖子

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

我有一个函数(实际上是这个函数的多个实例),但有时它可能返回多个元素的列表,有时它可能返回单个元素。我希望该函数每次都返回一个数组 ( [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 …
Run Code Online (Sandbox Code Playgroud)

powershell powershell-5.0

3
推荐指数
1
解决办法
287
查看次数

标签 统计

powershell ×1

powershell-5.0 ×1