Powershell如何重载数组索引运算符? [英] Powershell How to Overload Array Index Operator?

查看:110
本文介绍了Powershell如何重载数组索引运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

而且,我想这样做:

$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?

谢谢!

推荐答案

最简单的方法是从

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)) {}
}

演示:

$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

这篇关于Powershell如何重载数组索引运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆