我無法推送到 $filepaths,不明白為什么:
$filepaths=@()
$files= @('file1.text','file2.txt')
foreach ($file in $files) {
$filepaths.add("c:\test\" $file)
}
$filepaths
uj5u.com熱心網友回復:
@()是一個System.Array(一個固定的集合),從這個類的方法的備注中讀取:.Add
通常,
IList.Add實作將成員添加到集合中。但是,由于陣列具有固定大小(IsFixedSize屬性始終回傳 true),因此此方法始終會引發NotSupportedException例外。
PowerShell 為我們提供了使用運算子使用新元素重新創建陣列的能力,但是不推薦這樣做,原因在這個答案中得到了很好的解釋。 =
您可以將列舉的輸出分配給變數:
$filepaths = foreach($file in 'file1.txt', 'file2.txt') {
"c:\test\" $file
}
$filepaths
在此示例中,PowerShell 將為 動態分配型別$filepaths,如果從列舉中回傳 1 個元素,它將是string,對于多個元素,它將成為object[]( Array)。
或者使用允許添加新元素的集合,例如ArrayListor List<T>:
$filepaths = [Collections.Generic.List[string]]::new()
foreach($file in 'file1.txt', 'file2.txt') {
$filepaths.Add("c:\test\" $file)
}
$filepaths
在這里,$filepaths將始終是型別List`1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/479348.html
標籤:电源外壳
