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
相关产品推荐
相关产品推荐

