【问题标题】:Inheritance from .NET class in PowerShell从 PowerShell 中的 .NET 类继承
【发布时间】:2021-03-15 23:30:00
【问题描述】:

我有一个应用程序,我在其中使用来自 System.Collections.Generic.HashSet 的 HashSet,但想为其添加功能。

我正在尝试使用类继承来创建HashSet 的子类,但失败得很惨。

我一定是错误地声明了类名,但找不到从集合类型类继承的其他示例。

using namespace System.Collections.Generic

class StatusBucket : System.Collections.Generic.HashSet[HashSet[object]] {
    [array] toArray() {
        $array = [object[]]::new($this.count)
        foreach ($value in $this) {
            $array.Add($value)
        }
        return $array
    }
}

$setValues = @('1', '2')

$testHashSet = [HashSet[object]]::new($ids) # Works as expected
Write-Host $testHashSet

$testStatusBucket = [StatusBucket[object]]::new($ids) # Fails

【问题讨论】:

    标签: .net powershell inheritance collections subclass


    【解决方案1】:

    万一其他人遇到类似情况,我最终想通了。

    无需像在 C# 中那样指定集合的​​类型,如 <T>,您可以对括号执行相同的操作。如果您像通常在脚本中那样导入了命名空间,也可以省略它。所以类签名看起来像这样:

    using namespace System.Collections.Generic
    class StatusBucket : HashSet[Object] {
    }
    

    我的第二个问题是我无法实例化我的新类。经过一番挖掘,我发现构造函数不会自动继承。为了使用基类构造函数,您需要像这样使用 : base()

    using namespace System.Collections.Generic
    class StatusBucket : HashSet[Object] {
        StatusBucket() : base() {}
        # or to use additional arguments
        StatusBucket($oneArgument) : base($oneArgument) {}
    }
    

    所以在这种情况下,我的附加方法的最终结果最终看起来像这样:

    using namespace System.Collections.Generic
    class StatusBucket : HashSet[object] {
    
        StatusBucket() : base() { }
        StatusBucket($collection): base($collection) { }
    
        [array] toArray() {
            $array = [object[]]::new($this.count)
            $this.CopyTo($array)
            return $array
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多