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

PowerShell类构造函数无法分配变量值问题求助

PowerShell类构造函数赋值错误排查与解决

问题代码

class FileTransferStatus {

    $totalBytesToTransfer
    $bytesLeftToTransfer

    FileTransferStatus([System.IO.FileInfo[]]$files)
    {
        this.$totalBytesToTransfer = 0
        foreach ($file in $files) {
            this.$totalBytesToTransfer += $file.length
        }
        this.$bytesLeftToTransfer = this.$totalBytesToTransfer
    }
}

运行时构造函数最后一行报错:Variable is not assigned in the method.

错误含义

这个错误的核心原因是:在PowerShell类中访问成员属性时,不需要在this引用后给属性名加$符号。你写的this.$totalBytesToTransfer和this.$bytesLeftToTransfer会被PowerShell识别为未定义的局部变量,而非类的成员属性,因此提示变量在方法中未被赋值。

解决方法

移除成员属性名前的$,直接通过this.属性名的形式访问类成员。修正后的代码如下:

class FileTransferStatus {

    $totalBytesToTransfer
    $bytesLeftToTransfer

    FileTransferStatus([System.IO.FileInfo[]]$files)
    {
        this.totalBytesToTransfer = 0
        foreach ($file in $files) {
            this.totalBytesToTransfer += $file.length
        }
        this.bytesLeftToTransfer = this.totalBytesToTransfer
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:22:01