我在powershell中使用内联C#定义了一个类:
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; } }
}
"@
我可以实例化它: $ someClass = New-Object SomeClass -Property @ { '姓名'=“贾斯汀迪林”; “A”= 1; “B”= 5; };
但是我无法实例化它的列表:
$ listOfClasses = New-Object System.Collections.Generic.List [SomeClass];
这样做可以获得以下信息:
New-Object : Cannot find type [[System.Collections.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
答案 0 :(得分:2)
PowerShell似乎没有直接支持。这是a solution,它提供New-GenericObject
脚本;为了创造正确的类型,它做了一些反思。
答案 1 :(得分:0)
一种解决方案是简单地制作List&lt; SomeClass&gt; someClass定义中的工厂如下:
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>(); }
}
"@
然后你可以实例化一个像$listOfClasses = [SomeClass]::CreateList();
答案 2 :(得分:0)