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

PowerShell类方法实现咨询:SetString与PrintString功能疑问

PowerShell类方法实现答疑

问题解答

  1. 让SetString()接收传入字符串:
    在方法定义时添加参数声明,格式为[返回类型]方法名([参数类型]$参数名),调用时就能把括号里的字符串传入方法内部。

  2. PrintString()获取基础字符串:
    借助类的成员变量存储SetString传入的字符串,PrintString直接读取这个成员变量即可,实现两个方法的数据共享。

修正后的完整代码

class MyStringHandler {
    # 定义成员变量存储传入的字符串
    [string]_storedString

    # 接收字符串并存储到成员变量
    [void]SetString([string]$inputString) {
        $this._storedString = $inputString
    }

    # 读取存储的字符串,转大写后输出
    [void]PrintString() {
        Write-Host $this._storedString.ToUpper()
    }
}

# 测试示例
$handler = [MyStringHandler]::new()
$handler.SetString("gamarjoba")
$handler.PrintString()
# 输出: GAMARJOBA

代码说明

  • 类名改为MyStringHandler(避免和PowerShell内置的Object类冲突)
  • _storedString作为类的成员变量,专门用来保存传入的字符串
  • SetString用[void]作为返回类型(仅做存储操作无需返回值),通过$this._storedString将传入的参数赋值给成员变量
  • PrintString通过$this._storedString获取存储的字符串,调用ToUpper()转大写后输出

内容的提问来源于stack exchange,提问作者iharbasik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:25:21