【问题标题】:Powershell . Declare generic list with class defined using 'Add-Type'电源外壳 。声明使用“Add-Type”定义的类的通用列表
【发布时间】:2010-10-15 20:19:43
【问题描述】:

我正在尝试在 PowerShell 中声明 List,其中 Person 是使用 Add-Type 定义的:

add-type -Language CSharpVersion3 -TypeDefinition @"
    public class Person
    {
        public Person() {}

        public string First { get; set; }
        public string Last { get; set; }
    }
"@ 

这很好用:

New-Object Person
New-Object System.Collections.Generic.List``1[System.Object]

但是这条线失败了:

New-Object System.Collections.Generic.List``1[Person]

这里有什么问题?

【问题讨论】:

  • 对于其他想知道的人来说,失败的行(上面)在 Powershell 3.0 中有效(尽管我需要删除“-Language CSharpVersion3”,因为我在 Windows Server 2012 上运行了它)。

标签: generics collections powershell


【解决方案1】:

这是 New-Object 中的一个错误。这将帮助您更轻松地创建它们: http://www.leeholmes.com/blog/2006/08/18/creating-generic-types-in-powershell

更新:PowerShell 在版本 2 中添加了对此的支持:

PS > $r = New-Object "System.Collections.Generic.List[Int]"
PS > $r.Add(10)

【讨论】:

  • 欢迎来到 StackOverflow Lee!
【解决方案2】:

好吧,我试图创建一个 FileStream 对象列表,这是我的解决方案(基于 this link -- 它实际上描述了一种解决问题的方法):

$fs = New-Object 'System.Collections.Generic.List[System.IO.FileStream]'
$sw = New-Object 'System.Collections.Generic.List[System.IO.StreamWriter]'
$i = 0
while ($i < 10)
{
    $fsTemp = New-Object System.IO.FileStream("$newFileName",[System.IO.FileMode]'OpenOrCreate',[System.IO.FileAccess]'Write')
    $fs.Add($fsTemp)
    $swTemp = New-Object System.IO.StreamWriter($fsTemp)
    $sw.Add($swTemp)
    $i++
}

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2020-04-22
    相关资源
    最近更新 更多