传入空集会引发错误

Dav*_*ica 2 powershell set hashset powershell-4.0

HashSet我正在尝试按照答案在我的 powershell 脚本中使用 a 。

Add-Type -AssemblyName System.Core
$set= new-object 'System.Collections.Generic.HashSet[string]'
Run Code Online (Sandbox Code Playgroud)

但是如果我创建一个需要这样一个集合的函数

function foo([Parameter(Mandatory=$true)][Collections.Generic.HashSet[string]]$set){
Run Code Online (Sandbox Code Playgroud)

并传入集合

foo($set)
Run Code Online (Sandbox Code Playgroud)

如果为空,我会收到错误$set

Cannot bind argument to parameter '$set' because it is an empty collection.
    + CategoryInfo          : InvalidData: (:) [script.ps1], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyCollectionNotAllowed,script.ps1
Run Code Online (Sandbox Code Playgroud)

但如果我事先添加一些东西,$set我就不会遇到问题。

为什么参数不能绑定到空集,如何让它绑定到这样的集?

Mat*_*ewG 8

您可以使用以下属性将函数标记为允许空哈希表AllowEmptyCollection

function foo([Parameter(Mandatory=$true)][AllowEmptyCollection()][Collections.Generic.HashSet[string]]$set)
Run Code Online (Sandbox Code Playgroud)