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

2024-05-07

人们可以使用以下简单的表示法在 PowerShell 中调用许多 LINQ 方法:

[int[]] $numbers = 1..10000
[Linq.Enumerable]::Sum($numbers)

在调用中包含 lambda 甚至是一件相对简单的事情:

[Func[int,int]] $delegate = { $n = $args[0]; if ($n % 3) { $n } else { -$n } }
[Linq.Enumerable]::Sum($numbers, $delegate)

不过,我想知道的是如何调用genericPowerShell 中的 LINQ 方法:有可能吗? 我发现这个问题 https://stackoverflow.com/q/4241985/115690这似乎表明可以,但我还没有确定如何将该信息应用到 LINQ。 (另外,事实上,这是旧信息,PS 版本 5 很可能有一种更简洁的方法来做到这一点。)

那么如何才能调用[Linq.Enumerable]::Cast<T>(...) or [Linq.Enumerable]::OfType<T>(...)在 PowerShell 中正确吗?

2017.05.10 更新

好的,根据@Mathias 的评论,让我们坚持下去MakeGenericMethod。在 C# 中,这个咒语有效:

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:

[System.Type]::GetType("System.Linq.Enumerable")
[System.Type]::GetType("Linq.Enumerable")
[System.Type]::GetType("Enumerable")

我确信我错过了一些简单的事情;建议?


是的,PetSerAl 和 ejohnson 的评论当然都是正确的;我只是因为某种原因出现了心理障碍。因此,对于那些可能感兴趣的人来说,这是完整的解决方案:

$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)) 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 PowerShell 中调用静态通用 LINQ 扩展方法 的相关文章