从函数/脚本返回 ArrayList [英] Returning ArrayList from Function/Script

查看:33
本文介绍了从函数/脚本返回 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下脚本:

function f {
    [CmdletBinding()]Param()
    Write-Verbose 'f: Start'
    $t = New-Object 'System.Collections.ArrayList'
    Write-Verbose $t.GetType().Name
    return $t
}

$things = New-Object 'System.Collections.ArrayList'
$things.GetType().Name
$things = f -verbose
$things.GetType().Name

为什么最后一行的 $things 不是 ArrayList 类型?

Why wouldn't the $things be-of-type ArrayList at the final line?

推荐答案

输出集合(不仅仅是数组)导致 PowerShell 默认枚举它们 - 即集合的元素被一个一个发送到成功输出流.

Outputting collections (not just arrays) causes PowerShell to enumerate them by default - i.e., the collection's elements are sent one by one to the success output stream.

  • 如果您通过在变量中捕获输出来收集这些元素,您总是会得到一个常规的 PowerShell 数组 ([object[]]),除非只有 一个元素,按原样捕获.
  • If you collect these elements by capturing the output in a variable, you always get a regular PowerShell array ([object[]]), except if there's only one element, which is captured as-is.

为了防止这种情况 - 即输出一个集合作为一个整体 - 使用:

To prevent that - i.e., to output a collection as a whole - use:

Write-Output -NoEnumerate $t

一个更短、更有效但不太明显的替代方案是将集合包装在一个辅助的单元素数组中,使用 , 的一元形式,数组构造运算符,这会导致 PowerShell 枚举外部数组并按原样输出集合:

A shorter and more efficient, but less obvious alternative is to wrap the collection in an auxiliary single-element array with the unary form of ,, the array-construction operator, which causes PowerShell to enumerate the outer array and output the collection within as-is:

, $t    # implicit output, no Write-Output needed

这篇关于从函数/脚本返回 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆