开发者

Making a List<T> of a type created via Add-Type -TypeDefinition in powershell

I have a class that I define in inline C# in powershell:

Add-Type -TypeDefinition @"
    public class SomeClass {
        string name;
        public string Name { get { return name; } set { name = value; } }
        int a, b;
        public int A { get { return a; } set { a = value; } }
        public int B { get { return b; } set { b = value; } }
    }
"@

I can instantiate it: $someClass= New-Object SomeClass -Property @{ 'Name' = "Justin Dearing"; "A" = 1; "B" = 5; };

But I cannot instantiate a list of it:

$listOfClasses = New-Object System.Collections.Generic.List[SomeClass];

Doing so gets me the following:

New-Object : Cannot find type [[System.Collec开发者_开发技巧tions.Generic[SomeClass]]]: make sure the assembly containing this type is loaded.
At line:12 char:28
+ $listOfClasses = New-Object <<<<  [System.Collections.Generic[SomeClass]]
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand


It seems that is not directly supported in PowerShell. Here is a solution, which provides a New-GenericObject script; that does some reflection in order to create the correct type.


One solution is to simple make a List<SomeClass> factory in the SomeClass definition like so:

Add-Type -TypeDefinition @"
    using System.Collections.Generic;

    public class SomeClass {
        string name;
        public string Name { get { return name; } set { name = value; } }
        int a, b;
        public int A { get { return a; } set { a = value; } }
        public int B { get { return b; } set { b = value; } }

        public static List<SomeClass> CreateList () { return new List<SomeClass>(); }
    }
"@

Then you can instantiate a list like so $listOfClasses = [SomeClass]::CreateList();


read this:

http://blogs.msdn.com/b/thottams/archive/2009/10/12/generic-list-and-powershell.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜