向自定义User类泛型列表添加实例时出现Add方法重载错误
问题:向泛型列表添加自定义类实例时,Add方法报错
执行代码向[System.Collections.Generic.List[User]]类型的列表添加User实例时,出现以下错误:
Cannot find an overload for "Add" and the argument count: "1". At line:8 char:17 + $Users.Add($TEST) + ~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBest
自定义User类代码
class User { [System.IO.DirectoryInfo]$Root [String]$Username [Folder]$Outlook [Folder]$AppDataTemp [Folder]$Downloads [System.Int64]$Size User([System.IO.DirectoryInfo]$Dir){ $this.DirInfo = $Dir $this.Username = $Dir.Name } [void]GetOutlookDataFiles(){ $local:Path = "$($this.Root.FullName)\AppData\Local\Microsoft\Outlook\" $local:Query = @('*.ost', '*.nst') $this.Outlook = [Folder]::new($Path) $this.Outlook.GetFiles($Query) $this.Outlook.GetSize() } [void]GetAppDataTemp(){ $local:Path = "$($this.Root.FullName)\AppData\Local\Temp" $local:Query = @("*") $this.AppDataTemp = [Folder]::new($Path) $this.AppDataTemp.GetFiles($Query) $this.AppDataTemp.GetSize() } [void]GetDownloads(){ $local:Path = "$($this.Root.FullName)\Downloads" $local:Query = @("*") $this.AppDataTemp = [Folder]::new($Path) $this.AppDataTemp.GetFiles($Query) $this.AppDataTemp.GetSize() } }
创建实例并添加到列表的代码
$Users = [System.Collections.Generic.List[User]]::new() $DirInfo = [System.IO.DirectoryInfo]::new("$env:SystemDrive\Users\").GetDirectories() ForEach($Dir in $DirInfo){ if($Dir.Attributes.ToString().Replace(" ", "").Split(', ') -notcontains 'Hidden'){ $TEST = [User]::new($Dir) $TEST.GetOutlookDataFiles() $TEST.GetAppDataTemp() $TEST.GetDownloads() $Users.Add($TEST) } }
解决方法
1. 修复构造函数的属性赋值错误
User类构造函数中错误地给未定义的DirInfo属性赋值,应改为给类中已声明的Root属性赋值:
User([System.IO.DirectoryInfo]$Dir){ $this.Root = $Dir # 替换原$this.DirInfo = $Dir $this.Username = $Dir.Name }
原代码中$this.Root始终为null,后续调用GetOutlookDataFiles等方法时会触发空引用错误,导致$TEST实例处于无效状态,这是Add方法报错的核心原因。
2. 修复GetDownloads方法的属性赋值错误
GetDownloads方法中错误地将Downloads目录的Folder实例赋值给AppDataTemp属性,应改为赋值给Downloads属性:
[void]GetDownloads(){ $local:Path = "$($this.Root.FullName)\Downloads" $local:Query = @("*") $this.Downloads = [Folder]::new($Path) # 替换原$this.AppDataTemp = ... $this.Downloads.GetFiles($Query) $this.Downloads.GetSize() }
3. 可选:优化隐藏目录判断逻辑
原判断隐藏目录的代码可简化,避免冗余的字符串操作:
if (-not $Dir.Attributes.HasFlag([System.IO.FileAttributes]::Hidden)) { # 后续实例创建与添加逻辑 }
完成上述修复后,User实例可被正确创建和初始化,泛型列表的Add方法即可正常执行。
内容的提问来源于stack exchange,提问作者user23078090
相关产品推荐
相关产品推荐

