【问题标题】:Attempting to override the indexer for Powershell class试图覆盖 Powershell 类的索引器
【发布时间】:2020-10-27 23:12:42
【问题描述】:

我正在尝试创建一个继承的 Powershell 类

System.Collections.ICollection,我希望索引器返回类中 Arraylist 对象的元素。 C# 中的示例:

class ThingCollection : ICollection {
    private ArrayList ArrayOfThings = new ArrayList();
    ThingCollection() {}
    public void Add(Thing myThing) {
        this.Thing.Add(myThing);
    }
    // Below is what I want to implement in PowerShell
    public Thing this[int index] { 
        get {
            return (Thing) this.ArrayOfThings[index];
        }
    }
}

不工作的 Powershell:

Class ThingCollection : System.Collections.ICollection
{
    [System.Collections.ArrayList]$ArrayOfThings = `
        [System.Collections.ArrayList]::new()
    ThingCollection() {}
    [Void]Add([Thing]$myThing)
    {
        $this.ArrayOfThings.Add($myThing)
    }
    # Below is invalid code
    [Thing]this[[Int32]$index]
    {
        return $this.ArrayOfThings[$index]
    }
}

我试图在这里调整一个较旧问题的答案:https://stackoverflow.com/a/55435909
通过沿线的迭代试验

ThingCollection() : base([System.Collections.Generic.List[]]()) {}

例如:

[Thing]ThingCollection([Int32]$index) : base([System.Collections.Generic.List[Int32]]($index)) {}

错误:构造函数无法指定返回类型

等...但我到达那里,因为我真的不知道它是如何工作的。
可以选择创建 getItem 方法,但是直接实现索引器覆盖将非常有帮助。

我真诚地感谢任何帮助!

【问题讨论】:

  • 我的回答有帮助吗?

标签: c# powershell collections overriding


【解决方案1】:

根据 PowerShell 类的 documentation,似乎自定义索引器不是受支持的功能。

但是为什么不让整个类直接从ArrayList继承呢?

class ThingCollection : System.Collections.ArrayList
{
    ThingCollection() { }
}

用法:

# create
$things = New-Object ThingCollection
# or
$things = [ThingCollection]::new()

# store
[void]$things.Add($myThing)

# retrieve
$things[0]

# modify
$things[0] = $myOtherThing

【讨论】:

  • 嗨,Marsze,我很欣赏这个想法。我尝试以几种方式尝试使用 Arraylist,但问题是我需要数组成为对象的属性,而不是对象本身。这是因为 Arraylist 元素是自定义错误记录,并且这个包含错误记录的“ThingCollection”被设置为 System.Data.Common.DbException 对象的自定义属性。这一切都是为了创建一个包含非常详细的异常信息的自定义数据库异常。
  • @Aelinon10 简短回答:在 PowerShell 类中无法进行索引。但是您仍然可以在 C# 中编写自己的 .NET 类型并使用它。
猜你喜欢
  • 2021-06-11
  • 2017-11-17
  • 2011-10-30
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
相关资源
最近更新 更多