无法将类型 "System.Char[,]" 的 "System.Char[,]" 值转换为类型 "System.Char"

Cannot convert the "System.Char[,]" value of type "System.Char[,]" to type "System.Char"

我有一个简单的脚本,它创建二维字符数组,并调用函数,该函数应该用给定的字符填充该数组。

[int]$size = Read-Host "Please, enter the board size"

$playerBoard = New-Object 'char[,]' $size,$size

Fill-Boad-With-Symbol($playerBoard,'*',$size)

这里是函数


function   Fill-Boad-With-Symbol([char[,]]$board, [char]$symbol,[int]$boardSize){
    for ($i=0; $i -lt $boardSize; $i++) {
        for ($j=0; $j -lt $boardSize; $j++) {
            $board[$i,$j] = $symbol
        }
    }
}

但是在执行这段代码时出现以下错误:

  Cannot process argument transformation on parameter 'board'. Cannot convert the "System.Char[,]" value of type "System.Char[,]" to type "System.Char"
...
+ Fill-Boad-With-Symbol($playerBoard,'*',$size)

求解释,我做错了什么?

如我的评论所述,在 PowerShell 中,参数是位置参数或命名参数,您的第一个错误是您将参数传递给函数的方式。通过这样做:

Fill-Board-Symbol($playerBoard,'*',$size)

PowerShell 会将其解释为好像您正在传递一个 object[](对象 array),其中第一个元素 array[0] 将是 $playerBoard,第二个元素将是一个* 和第三个元素,函数 -Board 的第一个参数的 intchar[,].[= 的类型约束28=]

PowerShell 然后将尝试从 object[]char[,] 的类型转换,它会失败并出现您看到的异常。

示例:

鉴于这些变量:

$playerBoard = New-Object 'char[,]' 2,2
$symbol = '*'
$size = 2

将它们组合在一起(...)我们可以检查它的类型:

PS /> ($playerBoard, $symbol, $size).GetType()

IsPublic IsSerial Name         BaseType
-------- -------- ----         --------
True     True     Object[]     System.Array

如果我们尝试将其转换为 [char[,]]:

PS /> [char[,]]($playerBoard, $symbol, $size)

InvalidArgument: Cannot convert the "System.Char[,]" value of type "System.Char[,]" to type "System.Char".

尝试这样做:

[int]$size = Read-Host "Please, enter the board size"
$playerBoard = New-Object 'char[,]' $size,$size

function Fill-Board-With-Symbol {
param(
    [char[,]]$board,
    [char]$symbol,
    [int]$boardSize
)
    for ($i=0; $i -lt $boardSize; $i++) {
        for ($j=0; $j -lt $boardSize; $j++) {
            $board[$i,$j] = $symbol
        }
    }
    $board # => This is your output
}

$newBoard = Fill-Board-With-Symbol -Board $playerBoard -Symbol '*' -BoardSize $size
$newBoard