Powershell如何重载数组索引运算符?

2023-12-24

在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

那么,如何对数组的索引进行运算符重载呢? 这有可能吗?

Thanks!


最简单的方法是从System.Collections.ObjectModel.Collection<T> https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1

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

上面的结果是:

2
5
--- all elements:
1
2
5
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Powershell如何重载数组索引运算符? 的相关文章

随机推荐