Array.Find on powershell 阵列 [英] Array.Find on powershell array
问题描述
如何使用 Array.Find 方法在 PowerShell 中?
例如:
$a = 1,2,3,4,5[数组]::Find($a, { args[0] -eq 3 })
给予
找不到Find"和参数计数的重载:2".在行:3 字符:1+ [数组]::Find($a, { $args[0] -eq 3 })+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : NotSpecified: (:) [], MethodException+ FullQualifiedErrorId : MethodCountCouldNotFindBest
数组类具有我期望的方法,如下所示:
PS>[阵列] |获取成员 - 静态类型名称:System.Array名称 MemberType 定义---- ---------- ----------Find 方法 static T Find[T](T[] 数组,System.Predicate[T] 匹配)
是否应该将数组强制转换为其他内容以匹配 T[] 类型?我知道还有其他方法可以实现查找功能,但我想知道为什么这不起作用.
您需要将 ScriptBlock
转换为 Predicate[T]
.考虑以下示例:
[Array]::Find(@(1,2,3), [Predicate[int]]{ $args[0] -eq 1 })# 结果:1
您收到错误的原因是没有匹配的方法重载,在您传入 PowerShell ScriptBlock
的情况下.正如您在 Get-Member
输出中所指出的,没有接受 ScriptBlock
作为第二个参数的 Find()
方法重载.>
[Array]::Find(@(1,2,3), { $args[0] -eq 1 })
<块引用>
找不到Find"和参数计数的重载:2".在行:1 字符:17+ [数组]::Find(@(1,2,3), { $_ -eq 1 })+ ~~~~~+ CategoryInfo : NotSpecified: (:) [], MethodException+ FullQualifiedErrorId : MethodCountCouldNotFindBest
How can I use the Array.Find method in powershell?
For example:
$a = 1,2,3,4,5
[Array]::Find($a, { args[0] -eq 3 })
gives
Cannot find an overload for "Find" and the argument count: "2".
At line:3 char:1
+ [Array]::Find($a, { $args[0] -eq 3 })
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
The array class has the methods I expect, as given by:
PS> [Array] | Get-Member -Static
TypeName: System.Array
Name MemberType Definition
---- ---------- ----------
Find Method static T Find[T](T[] array, System.Predicate[T] match)
Should the array be casted to something else to match the T[] type? I know there are other ways to achieve the find functionality, but I was wondering why this doesn't work.
You need to cast the ScriptBlock
as a Predicate[T]
. Consider the following example:
[Array]::Find(@(1,2,3), [Predicate[int]]{ $args[0] -eq 1 })
# Result: 1
The reason that you received the error, is because there was no matching method overload, in the case where you're passing in a PowerShell ScriptBlock
. As you noted in your Get-Member
output, there is no Find()
method overload that accepts a ScriptBlock
as its second parameter.
[Array]::Find(@(1,2,3), { $args[0] -eq 1 })
Cannot find an overload for "Find" and the argument count: "2". At line:1 char:17 + [Array]::Find(@(1,2,3), { $_ -eq 1 }) + ~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBest
这篇关于Array.Find on powershell 阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!