简体   繁体   English

Powershell数组未清除

[英]Powershell array is not cleared

My source code: 我的源代码:

# $arr = @(); results in same behaviour
$arr = New-Object System.Collections.ArrayList;

$arr.Count;
$arr += "z";

$arr.Count;
$arr.Clear();
$arr.Count;

Output: 输出:

0 0
1 1
1 1

Powershell does some array-casting trickery when you do += , so the easy solution is to do $arr.Add("z") . 当你执行+= ,Powershell会做一些数组转换$arr.Add("z") ,所以简单的解决方案是执行$arr.Add("z") Then $arr.Clear() will act like you expect. 然后$arr.Clear()会像你期望的那样行事。

To clarify: 澄清:

  1. @() is a Powershell array. @()是一个Powershell数组。 It uses += , but you can't Clear it. 它使用+= ,但你无法Clear它。 (You can, however, do $arr = @() again to reset it to an empty array.) (但是,您可以再次执行$arr = @()将其重置为空数组。)
  2. ArrayList is the .NET collection. ArrayList是.NET集合。 It uses .Add , and you can Clear it, but for some reason if you += it, Powershell does some weird array coercion. 它使用.Add ,你可以Clear它,但出于某种原因,如果你+=它,Powershell会做一些奇怪的数组强制。 (If any experts care to comment on this, awesome.) (如果有任何专家对此发表评论,真棒。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM