【问题标题】:Unexpected array size [duplicate]意外的数组大小[重复]
【发布时间】:2019-10-29 09:53:49
【问题描述】:

我正在尝试用 Powershell 脚本制作一个简单的二十一点游戏,但发现我的 ArrayList 没有按预期运行。我想了解为什么我得到的答案与预期的不同。

函数内部的Write-Host $deck 调用按我的预期打印出甲板,52 个对象。到目前为止一切顺利。

然而,当调用Write-Host $myDeck 时,奇怪的部分开始了。它会做的是,它会首先打印 0...51,然后是我的实际套牌。因此,我的ArrayList 中没有 52 个对象,而是得到 104 (52+52)。谁能解释这里到底发生了什么?因为我觉得这超级混乱。

function Get-Deck(){

    $ranks = 2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"
    $suits = "Spade","Heart","Diamond","Club"
    $deck = [System.Collections.ArrayList]::new()

    foreach($rank in $ranks){
        foreach($suit in $suits){
            $card = $rank , $suit
            $deck.Add($card)
        }
    }

    Write-Host $deck #prints out the actual array with 52 cards. 
    return $deck

}

$myDeck = Get-Deck
Write-Host $myDeck #prints out: 0 1 2 3 4 5 6 7 ... 51 2 Spade 2 Heart 2 Diamond ... Ace Club

【问题讨论】:

  • 这是产生它的方法。尝试如下修改这一行: $deck.Add($card) |外空

标签: arrays powershell arraylist


【解决方案1】:

意外的输出是由ArrayList.Add() 引起的。函数原型是这样的,

public virtual int Add (object value);

请注意,它有一个非 void 返回类型,int,它是添加值的 ArrayList 索引。

$deck.Add($card) 被调用时,返回值留在管道上并最终在arraylist 中。要解决此问题,请将返回值分配给显式变量,传递给 null 或强制转换为 void。有一些陷阱,请参阅another an answer 关于这些。这些中的任何一个都应该起作用。像这样,

$null = $deck.Add($card) # Preferred, (ab)uses automatic variable
[void]$deck.Add($card) # Works too
$deck.Add($card) | out-null # Works, but is the slowest option
$foo = $deck.Add($card) # Use this if you need the index value

【讨论】:

  • 很好,虽然值得一提的是 $null = $deck.Add($card) 用于输出抑制 - 它在语法上很简单(不像 [void],可能需要 (...))和快速(不像 Out-Null>$null) - this answer 详细讨论了输出抑制选项。
猜你喜欢
  • 1970-01-01
  • 2012-10-31
  • 2022-11-01
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 2018-05-12
相关资源
最近更新 更多