在PowerShell 5中,是否可以为类声明泛型属性?

时间:2016-10-24 20:54:03

标签: class powershell generics powershell-v5.0

PowerShell version 5引入了Class关键字,可以更轻松地在PowerShell中创建自定义类。该公告仅提供a brief summary on properties

  

所有属性都是公开的。属性需要换行符或分号。如果未指定对象类型,则属性类型为object。

到目前为止一切顺利。这意味着我可以轻松创建一个看起来像这样的类:

Class Node
{
    [String]$Label
    $Nodes
}

我遇到问题的地方是,如果没有为$Nodes指定类型,则默认为System.Object。我的目标是使用System.Collections.Generic.List类型,但到目前为止还没有弄清楚如何这样做。

Class Node
{
    [String]$Label
    [System.Collections.Generic.List<Node>]$Nodes
}

上述结果导致了一连串的问题:

At D:\Scripts\Test.ps1:4 char:36
+     [System.Collections.Generic.List<Node>]$Nodes
+                                    ~
Missing ] at end of attribute or type literal.
At D:\Scripts\Test.ps1:4 char:37
+     [System.Collections.Generic.List<Node>]$Nodes
+                                     ~
Missing a property name or method definition.
At D:\Scripts\Test.ps1:4 char:5
+     [System.Collections.Generic.List<Node>]$Nodes
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Missing closing '}' in statement block or type definition.
At D:\Scripts\Test.ps1:5 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : EndSquareBracketExpectedAtEndOfAttribute

这让我想到如何在PowerShell 5中为属性使用泛型类型?

1 个答案:

答案 0 :(得分:4)

在制作我的问题时,我偶然发现answer which details how to create Dictionary objects in PowerShell 2

$object = New-Object 'system.collections.generic.dictionary[string,int]'

特别值得注意的是,使用<>而不是使用[]进行通用声明。切换我的班级声明以使用square brackets代替angle brackets解决了我的问题:

Class Node
{
    [String]$Label
    [System.Collections.Generic.List[Node]]$Nodes
}
相关问题