创建 PowerShell Collections.Generic.IEnumerable[string] 错误

Create a PowerShell Collections.Generic.IEnumerable[string] error

我无法在 PowerShell 上创建 IEnumerable。

我的目标是另一个 issue/type,但帮我解决这个 "simple"。

C:\Users\Me> $var = New-Object Collections.Generic.IEnumerable[string]
New-Object : A constructor was not found. Cannot find an appropriate constructor for type Collections.Generic.IEnumerable[string].
At line:1 char:8
+ $var = New-Object Collections.Generic.IEnumerable[string]
+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

任何人都可以澄清我在哪里或哪里做错了吗?

最终对象有一个 属性 和 Collections.Generic.IEnumerable[...] 所以这就是为什么使用这种类型。

IEnumerable[TypeParameter]是一个接口,一个不能实例化的抽象类型。

如果您想要实现 IEnumerable[string] 的通用集合实例,请创建 List[string]:

$var = New-Object System.Collections.Generic.List[string]

如果您使用 PowerShell 5.0 和更新版本的 ::new() 方法,您可以跳过 System 命名空间前缀:

$var = [Collections.Generic.List[string]]::new()
# these will resolve to the same type
$var = [System.Collections.Generic.List[string]]::new()