列一个清单通过 powershell 中的 Add-Type -TypeDefinition 创建的类型
我有一个在 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= 新对象 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
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.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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PowerShell 似乎不直接支持。这是一个解决方案,提供一个 New-GenericObject 脚本;它会进行一些反射以创建正确的类型。
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.一种解决方案是简单地创建一个 List。工厂在 SomeClass 定义中,如下所示:
然后您可以像这样实例化一个列表
$listOfClasses = [SomeClass]::CreateList();
One solution is to simple make a List<SomeClass> factory in the SomeClass definition like so:
Then you can instantiate a list like so
$listOfClasses = [SomeClass]::CreateList();
阅读此内容:
http:// blogs.msdn.com/b/thottams/archive/2009/10/12/generic-list-and-powershell.aspx
read this:
http://blogs.msdn.com/b/thottams/archive/2009/10/12/generic-list-and-powershell.aspx