【发布时间】: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