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

在PowerShell中实现out与ref参数并转写C#的IPropertyBag实现类

把C#的ConfigurationPropertyBag转换为PowerShell类(处理ref/out参数)

没问题,我来帮你把这个实现IPropertyBag的C#类转换成PowerShell类,同时解决out和ref参数的处理问题。

PowerShell中ref/out参数的处理逻辑

PowerShell没有直接对应C#的out关键字,但可以通过[ref]类型参数实现完全等效的功能:

  • 对于C#的out参数:在PowerShell中声明为[ref]类型参数,调用时传递[ref]包装的变量,方法内部通过$参数名.Value赋值输出结果。
  • 对于C#的ref参数:直接使用[ref]类型参数即可,和C#一样允许读写传递的变量值。

改写后的PowerShell类代码

class ConfigurationPropertyBag : IPropertyBag {
    # 内部存储属性的HybridDictionary
    hidden [System.Collections.Specialized.HybridDictionary] $properties

    # 构造函数
    ConfigurationPropertyBag() {
        $this.properties = [System.Collections.Specialized.HybridDictionary]::new()
    }

    # 实现IPropertyBag的Read方法(对应C#的out参数)
    [void] Read([string] $propName, [ref] $ptrVar, [int] $errLog) {
        # 将字典中的值赋值给ref参数的Value属性
        $ptrVar.Value = $this.properties[$propName]
    }

    # 实现IPropertyBag的Write方法(对应C#的ref参数)
    [void] Write([string] $propName, [ref] $ptrVar) {
        # 将ref参数的Value添加到字典中
        $this.properties.Add($propName, $ptrVar.Value)
    }
}

关键细节说明

  1. 接口实现:确保类继承IPropertyBag,如果你的PowerShell环境中未加载该接口所在的程序集(比如System.Windows.Forms),需要先执行:
    Add-Type -AssemblyName System.Windows.Forms
    
  2. hidden修饰符:用hidden标记$properties字段,避免它在PowerShell的默认成员枚举中显示,和C#的internal访问级别语义接近。
  3. 参数处理:
    • Read方法中,通过$ptrVar.Value给调用方的变量赋值,完全等效C#的out参数行为。
    • Write方法中,读取$ptrVar.Value获取传递的变量值,和C#的ref参数一致。

使用示例

# 创建属性包实例
$configBag = [ConfigurationPropertyBag]::new()

# 写入属性
$myValue = "DatabaseConnectionString"
$configBag.Write("ConnString", [ref]$myValue)

# 读取属性
$readValue = $null
$configBag.Read("ConnString", [ref]$readValue, 0)

# 输出结果
$readValue # 会打印 "DatabaseConnectionString"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:29:13