Powershell How to Overload Array Index Operator?

只谈情不闲聊 提交于 2021-02-07 14:14:50

问题


In Powershell, how do you overload the indexing of an array operator?

Here is what I am doing now:

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

And, I want to do this:

$myThreeArray = New-Object ThreeArray

Write-Host $myThreeArray[1] # 2

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

So, how do I operator overload the indexing of an array? Is it even possible at all?

Thanks!


回答1:


The simplest approach is to derive from System.Collections.ObjectModel.Collection<T>

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

To demonstrate:

$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

The above yields:

2
5
--- all elements:
1
2
5


来源:https://stackoverflow.com/questions/55435300/powershell-how-to-overload-array-index-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!