arrays - PowerShell:为什么一个参数上的 [Parameter(Mandatory = $True)] 会影响另一个参数的类型转换行为?
问题描述
有人知道为什么参数 $a 上的强制属性会影响参数 $b 的类型转换行为吗?在示例中,数组应转换为字符串。
function test ([Parameter(Mandatory = $True)] [string] $a, [string] $b) {
$a; $b
}
$b = "a", "b", "c"
test -a "my string" -b $b
执行此代码块时,会产生错误:测试:无法处理参数“b”上的参数转换。无法将值转换为 System.String 类型。在行:1 字符:31
如果我从 $a 中删除 Mandatory 属性,它可以正常工作:
function test ([string] $a, [string] $b) {
$a; $b
}
$b = "a", "b", "c"
test -a "my string" -b $b
提前感谢您的反馈
解决方案
By adding the [Parameter()]
attribute, you are implying the [CmdletBinding()]
attribute (i.e. turning the function into an Advanced Function). If you look at the source code for the behaviour when using [CmdletBinding()]
, you'll see that it explicitly disallows conversion of an array to a string, which is what you're trying to do.
To see that it is specific to arrays, try, for example, $b = Get-Date
(i.e. pass a DateTime
object). The conversion to string works fine.
推荐阅读
- android - 如何使用箭头键/dpad 禁用菜单导航的音效?
- python - 在 Beautiful Soup 中使用 find 方法解析不一致
- android - 谷歌日历没有返回其中创建的事件的当前状态
- reactjs - 当应用程序中使用了两个 BrowserRouter 时 Histoy.Push() 不会导航到组件
- angular - 使用 FormControl.patchValue 进行 p-dropdown 选择 - 始终选择第一个值
- python - python requests.get 挂起,直到长 http 请求超时
- elasticsearch - 首次安装的 Elasticsearch 无法启动
- python - 尝试在 Blender 中使用完整的 Python 发行版
- cmake - 如何在 CMAKE 中创建新的 CFLAG 并在代码中将其用作 #ifdef
- flutter - 为什么调用网络请求时第一次点击按钮没有发出加载状态?