You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中ArrayList反转失效:为何结果不符合预期

问题原因及解决方法

你的问题出在调用了错误的反转方法:

你使用的[array]::Reverse($arr)是针对System.Array类型的静态方法,当你把System.Collections.ArrayList对象传入这个方法时,PowerShell会自动将ArrayList转换为一个临时的普通数组副本,这个方法实际反转的是这个临时数组,而不是你原本的ArrayList集合,所以原集合完全没变化,两次输出自然都是Apple。

正确的解决方式

直接调用ArrayList自身的实例方法Reverse(),它会直接修改原集合:

[System.Collections.ArrayList]$arr = @()
$arr.Add("Apple") | Out-Null
$arr.Add("Orange") | Out-Null
$arr.Add("Banana") | Out-Null

# Print the first element
$arr[0]

# Reverse the ArrayList using its own method
$arr.Reverse()

# Print the first element
$arr[0]

执行这段代码后,输出会是Apple和Banana,符合你的预期。

内容的提问来源于stack exchange,提问作者user9924807

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 21:25:07