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
相关产品推荐
相关产品推荐

