web-dev-qa-db-ja.com

パワーシェル 。 'Add-Type'を使用して定義されたクラスでジェネリックリストを宣言する

Add-Typeを使用してPersonが定義されているPowerShellでListを宣言しようとしています。

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]

ここで何が問題になっていますか?

21
alex2k8

これは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)
34
LeeHolmes

まあ、私は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++
}

お役に立てば幸いです。

9
Girardi