在PowerShell中调用静态通用LINQ扩展方法

编程入门 行业动态 更新时间:2024-10-24 19:28:01
本文介绍了在PowerShell中调用静态通用LINQ扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

一个简单的符号就可以在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扩展方法

本文发布于:2023-06-11 23:32:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/645305.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法   PowerShell   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!