Powershell 如何编写调用其构造函数的类方法

问题描述 投票:0回答:1

我总结了我的要求。 假设我有一个处理文本文件并在某些行上应用进程的类。 在这些方法中,提取文本的一部分并应返回此类的实例,但仅限于原始文件的这一部分。 所以我有一个方法会调用它自己的构造函数。 我有一种行不通的感觉。当然可以使用其他语言,但不能在 PowerShell 中使用。 我想做的事:

Class MyClass {

   MyClass([string|]] lines) {

   }

   [MyClass]MyMethod {
      return [MyClass]::new( somelines)
   }

}

[MyClass]$obj1 = [MyClass]::new( ( get-content "myfile.txt"))
[MyClass]$obj2= $obj1.MyMethod()

我不喜欢我的解决方案:

Class MyClass {

   MyClass([string|]] $lines) {

   }
   [String[]]MyMethod {
       return somelines
   }
}


[MyClass]$obj1 = [MyClass]::new( ( get-content "myfile.txt"))
[string[]]$part = $obj1.MyMethod()
[MyClass]$obj2 = [MyClass]::new( $part)
powershell object
1个回答
0
投票

您所描述的完全可行:

class MyClass {
  [string[]]$Lines

  MyClass([string[]]$lines){
    $this.Lines = $lines
  }

  [MyClass]MyMethod([int]$from, [int]$to) {
    if ($from -lt 0) {
      throw [System.ArgumentOutOfRangeException]::new('from')
    }
    if ($to -lt $from -or $to -ge $this.Lines.Count) {
      throw [System.ArgumentOutOfRangeException]::new('to')
    }

    return [MyClass]::new($this.Lines[$from..$to])
  }
}

示例:

$fileContents = @'
Line 1
Line 2
Line 3
Line 4
Line 5
'@ -split '\r?\n'

$myInstance = [MyClass]::new($fileContents)
$mySubset = $myInstance.MyMethod(1, 3)

$myInstance.Lines # returns `Line1` through `Line 5`
$mySubset.Lines   # returns `Line2` through `Line 4`
© www.soinside.com 2019 - 2024. All rights reserved.