You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell类方法中调用自身构造函数返回类实例?

PowerShell类方法返回自身实例的实现

我需要实现一个处理文本文件的PowerShell类,要求其中一个方法提取文本的部分内容后,直接返回包含该内容的类实例(即方法内部调用类自身的构造函数)。我原本以为这种写法在PowerShell中无法生效(类似写法在其他语言可行)。

期望的代码结构

Class MyClass {
   MyClass([string[]] $lines) {
       # 构造函数逻辑:将传入的文本行存储到类成员
       $this.Lines = $lines
   }

   [MyClass] MyMethod() {
       # 示例:提取前5行作为目标内容
       $somelines = $this.Lines[0..4]
       return [MyClass]::new($somelines)
   }

   # 类成员:存储文本行,供方法访问使用
   [string[]]$Lines
}

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

当前不满意的解决方案

目前我只能通过让方法返回字符串数组,再手动实例化新对象的方式实现,但这种方式需要额外步骤,不够简洁:

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

   [string[]] MyMethod() {
       $somelines = $this.Lines[0..4]
       return $somelines
   }

   [string[]]$Lines
}

[MyClass]$obj1 = [MyClass]::new((Get-Content "myfile.txt"))
[string[]]$part = $obj1.MyMethod()
[MyClass]$obj2 = [MyClass]::new($part)

正确的实现方式

实际上PowerShell完全支持类方法返回自身类型的实例,你之前的期望代码只是存在语法错误:方法定义时缺少了括号(),同时需要在类中添加成员变量来存储传入的文本行,供方法调用使用。修正后的代码(如上面的「期望的代码结构」)可以正常运行,直接通过方法返回新的MyClass实例,无需额外手动实例化步骤。

内容的提问来源于stack exchange,提问作者Marc M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:12:14