如何在powershell中使用Array.Find方法?
例如:
$a = 1,2,3,4,5
[Array]::Find($a, { args[0] -eq 3 })
Run Code Online (Sandbox Code Playgroud)
给
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
Run Code Online (Sandbox Code Playgroud)
数组类具有我期望的方法,如下所示:
PS> [Array] | Get-Member -Static
TypeName: System.Array
Name MemberType Definition
---- ---------- ----------
Find Method static T Find[T](T[] array, System.Predicate[T] match)
Run Code Online (Sandbox Code Playgroud)
数组是否应该转换为与T []类型相匹配的其他内容?我知道有其他方法可以实现查找功能,但我想知道为什么这不起作用.
Neo*_*isk 17
没有必要使用Array.Find,常规where子句可以正常工作:
$a = @(1,2,3,4,5)
$a | where { $_ -eq 3 }
Run Code Online (Sandbox Code Playgroud)
或者这(由@mjolinor建议):
$a -eq 3
Run Code Online (Sandbox Code Playgroud)
或者这个(返回$true或$false):
$a -contains 3
Run Code Online (Sandbox Code Playgroud)
Where 子句支持任何类型的对象,而不仅仅是基本类型,如下所示:
$a | where { $_.SomeProperty -eq 3 }
Run Code Online (Sandbox Code Playgroud)
你需要把它ScriptBlock作为一个Predicate[T].请考虑以下示例:
[Array]::Find(@(1,2,3), [Predicate[int]]{ $args[0] -eq 1 })
# Result: 1
Run Code Online (Sandbox Code Playgroud)
您收到错误的原因是,在您传入PowerShell的情况下,没有匹配的方法重载ScriptBlock.正如您在Get-Member输出中所指出的那样,没有Find()方法重载接受a ScriptBlock作为其第二个参数.
[Array]::Find(@(1,2,3), { $args[0] -eq 1 })
Run Code Online (Sandbox Code Playgroud)
找不到"查找"的重载和参数计数:"2".在行:1 char:17 + [Array] :: Find(@(1,2,3),{$ _ -eq 1})+ ~~~~ + CategoryInfo:NotSpecified:(:) [],MethodException + FullyQualifiedErrorId:MethodCountCouldNotFindBest
| 归档时间: |
|
| 查看次数: |
26164 次 |
| 最近记录: |