一个简单的符号就可以在PowerShell中调用许多LINQ方法:
One can call many LINQ methods in PowerShell with this simple notation:
[int[]] $numbers = 1..10000 [Linq.Enumerable]::Sum($numbers)在通话中包含lambda甚至是相对简单的事情:
It is even a relatively simple matter to include a lambda in a call:
[Func[int,int]] $delegate = { $n = $args[0]; if ($n % 3) { $n } else { -$n } } [Linq.Enumerable]::Sum($numbers, $delegate)不过,我想知道的是如何从PowerShell调用通用 LINQ方法:甚至可能吗? 我发现这个SO问题似乎表明可以,但是我还没有确定如何将该信息应用于LINQ. (此外,由于这是旧信息,因此PS版本5很有可能采用一种更清洁的方式来实现.)
What I am wondering, though, is how to call a generic LINQ method from PowerShell: is it even possible? I found this SO question that seems to indicate one can, but I have not determined how to apply that info to LINQ. (Plus, the fact that that is old information, it is quite possible that with PS version 5 there is a cleaner way to do it.)
那么如何在PowerShell中正确调用[Linq.Enumerable]::Cast<T>(...)或[Linq.Enumerable]::OfType<T>(...)?
So how could one call [Linq.Enumerable]::Cast<T>(...) or [Linq.Enumerable]::OfType<T>(...) properly in PowerShell?
2017.05.10更新
好的,因此基于@Mathias注释,让我们继续使用MakeGenericMethod.在C#中,这种咒语有效:
OK, so based on @Mathias comment, let's stick with MakeGenericMethod. In C#, this incantation works:
var ofTypeForString = typeof(System.Linq.Enumerable).GetMethod("OfType").MakeGenericMethod(typeof(string)); var stuff = new object[] { 1.2, "abc", "def" }; var results = ofTypeForString.Invoke(null, new[] { stuff });我仍然缺少的部分是如何将typeof(System.Linq.Enumerable)转换为PowerShell.我认为其中至少有一个应该可以工作,但是它们都返回null:
The piece I am still missing is how to translate typeof(System.Linq.Enumerable) to PowerShell. I thought that at least one of these should work but they all return null:
[System.Type]::GetType("System.Linq.Enumerable") [System.Type]::GetType("Linq.Enumerable") [System.Type]::GetType("Enumerable")我确定我缺少一些简单的东西;建议?
I am sure I am missing something simple; suggestions?
推荐答案是的,当然,PetSerAl和ejohnson的评论都是正确的.由于某种原因,我只是有一个精神障碍.因此,对于那些有兴趣的人,这里是完整的解决方案:
Yes, both PetSerAl and ejohnson's comments are correct, of course; I just had a mental block for some reason. So here is the complete solution for those who may be interested:
$stringType = "".GetType() # set to your target type $ofTypeForString = [Linq.Enumerable].GetMethod("OfType").MakeGenericMethod($stringType) $stuff = @("12345", 12, "def") # The last comma below wraps the array arg $stuff within another array $ofTypeForString.Invoke($null, (,$stuff))更多推荐
在PowerShell中调用静态通用LINQ扩展方法
发布评论