似乎无法将泛型集合与 PowerShell 类一起使用 [英] Can't seem to use generic collection with a PowerShell class
问题描述
我正在尝试调用 List[T](IEnumerable)
像这样直接将一个项目添加到初始的List
,其中T
是我编写的 PowerShell 类(以下示例使用类名 Thing
:
I'm trying to invoke the List[T](IEnumerable)
directly adding an item to the initial List
like so, where T
is a PowerShell class I've written (the below example uses the class name Thing
:
$someObject = Get-Thing # returns a single object
$list = [List[Thing]]::new(@( $someObject ))
然而,这会产生一个错误,表明它找不到这个构造函数的重载:
However, this yields an error suggesting it can't find the overload for this constructor:
找不到List`1"的重载;和参数计数:1".
Cannot find an overload for "List`1" and the argument count: "1".
将 List[T]
设置为 Object
类有效,但是:
Setting List[T]
to the Object
class works, however:
$someObject = Get-Thing
$list = [List[Object]]::new(@( $someObject ))
虽然这有效,但我不确定为什么我无法使用我的 PowerShell 类作为类型.我的理解是 仅上下文-绑定类型和(默认情况下)嵌套类型 不能与泛型一起使用,但以下显示我的类不是 ContextBoundObject
:
While this works, I'm unsure why I'm unable to use my PowerShell class as the type. My understanding is that only context-bound types and (by default) nested types are unable to be used with generics, but the following shows that my class is not a ContextBoundObject
:
class Thing {
$Name
Thing($name) {
$this.Name = $name
}
}
$thing = [Thing]::new('Bender')
$thing -is [System.ContextBoundObject] # ==> False
我不确定 PowerShell 类是否是某种嵌套类型,并且 about_Classes 没有提到嵌套类型.
I'm not certain if a PowerShell class would be a nested type of some sort, and about_Classes does not mention nested types.
推荐答案
我不确定为什么我不能使用我的 PowerShell 类作为类型
I'm unsure why I'm unable to use my PowerShell class as the type
数组子表达式运算符 @()
返回其结果为 [object[]]
- 满足参数类型 [IEnumerable[object]] 的类型
- 这就是为什么当您使用 [object]
作为接收集合类型的类型参数时它总是有效的原因.
The array subexpression operator @()
returns its results as [object[]]
- a type which satisfies the argument type [IEnumerable[object]]
- which is why it always works when you use [object]
as the type parameter for the receiving collection type.
那么,该怎么办?
如果数组仅由 [Thing]
组成,您可以显式转换为实现 [IEnumerable[Thing]]
的更具体的集合类型:>
If the array consists only of [Thing]
's, you can explicitly cast to a more specific collection type that implements [IEnumerable[Thing]]
:
$list = [List[Thing]]::new([Thing[]]@( $someObject ))
这篇关于似乎无法将泛型集合与 PowerShell 类一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!