在Powershell中,如何重载数组运算符的索引?

这是我现在正在做的事情:

class ThreeArray {

    $myArray = @(1, 2, 3)

    [int] getValue ($index) {
        return $this.myArray[$index]
    }

    setValue ($index, $value) {
        $this.myArray[$index] = $value
    }
}

$myThreeArray = New-Object ThreeArray

Write-Host $myThreeArray.getValue(1) # 2

$myThreeArray.setValue(2, 5)
Write-Host $myThreeArray.getValue(2) # 5

而且,我想这样做:
$myThreeArray = New-Object ThreeArray

Write-Host $myThreeArray[1] # 2

$myThreeArray[2] = 5
Write-Host $myThreeArray[2] # 5

那么,如何操作符重载数组的索引?
甚至有可能吗?

谢谢!

最佳答案

最简单的方法是从 System.Collections.ObjectModel.Collection<T> 派生

class ThreeArray : System.Collections.ObjectModel.Collection[string]
{
  ThreeArray() : base([System.Collections.Generic.List[string]](1, 2, 3)) {}
}

展示:
$myThreeArray = [ThreeArray]::new() # same as: New-Object ThreeArray

$myThreeArray[1]     # print the 2nd element

$myThreeArray[2] = 5 # modify the 3rd element...
$myThreeArray[2]     # and print it

'--- all elements:'
$myThreeArray        # print all elmements

以上 yield :
2
5
--- all elements:
1
2
5

07-26 05:39