问题
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