Generics 如何在PowerShell中向下转换函数的返回值?

Generics 如何在PowerShell中向下转换函数的返回值?,generics,function,powershell,casting,Generics,Function,Powershell,Casting,我暂时有个有趣的问题。假设我有这个函数 function GetAllFiles($creds, $fld){ $newFiles = New-Object "system.collections.generic.list[string]" ... other stuff which adds entires return $newFiles } 在调用端执行时 $files = GetAllFiles $creds $fld $files.Remove("AnExistin

我暂时有个有趣的问题。假设我有这个函数

function GetAllFiles($creds, $fld){
   $newFiles = New-Object "system.collections.generic.list[string]"
   ... other stuff which adds entires
   return $newFiles
}
在调用端执行时

$files = GetAllFiles $creds $fld
$files.Remove("AnExistingEntry")
我明白了

dir ls.ps1:方法调用失败,因为[System.Object[]不包含meth 名为“删除”的od

当我这样做的时候 $newFiles.GetType()

如何将其设置为“system.collections.generic.list[string]”返回


谢谢,该对象类型没有“删除”方法。我想你看到的是元素的成员:

$files | gm将获取数组第一个元素的成员(管道将展开数组,最后对第一个元素执行gm)

gm-inputobject$files将显示数组的成员,并且“remove”不在该对象类型的方法中

在return语句中试试这个,看看它是否保持了数组的完整性,而不是在return语句中展开它


return,$newFiles

我的想法是我在函数外部释放了system.collections.generic.list[string]我仍然获取>>>dir ls.ps1:方法调用失败,因为[system.Object[]不包含名为“Remove”的方法。Powershell将自动尝试“展开”将数组转换为一个元素字符串。逗号强制结果为一个元素的数组,即一个元素是原始数组。当它“展开”时,最终结果是原始数组作为包含它的数组的元素被完整地传递(如果有意义的话)。
IsPublic IsSerial Name                                     BaseType                
-------- -------- ----                                     --------                
True     True     Object[]                                 System.Array