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

标签 arrays powershell class indexing overloading

在 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

以上产生:
2
5
--- all elements:
1
2
5

关于arrays - Powershell 如何重载数组索引运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55435300/

相关文章:

powershell - 如何在Windows 10中设置静态IP地址?

c++ - 将数组复制到函数 C++

python - 什么是 np.uint8?

windows - 使用脚本在 Powershell 命令提示符中填写多个答案

java - 在类中使用静态方法时没有输出(其中没有 main 函数的类)

java - 在自己的主体中测试类是个好主意吗?

class - 在 Dart 中,从变量调用静态方法时出现问题

c - 如何将未知大小的字符串数组传递给 C 中的函数

字符变量[] = {0};和 char var[1];在 C 中等价?

visual-studio-2010 - 如何从 PowerShell 脚本触发 T4 模板