gpt4 book ai didi

powershell - Powershell与管道中的可枚举

转载 作者:行者123 更新时间:2023-12-03 01:20:43 26 4
gpt4 key购买 nike

我感到很困惑。我不明白为什么Powershell中的foreach行为与C#如此不同。

这个简单的代码不会产生任何输出:

@{a=1; b=2} | %{ $_.key }

我在Linqpad中使用C#进行的近似处理得到了我期望的输出:
var ht = new Hashtable();
ht["a"] = 1;
ht["b"] = 2;

foreach (DictionaryEntry kvp in ht)
{
kvp.Key.Dump();
}

// output

a
b

如果我枚举哈希表的Keys成员,我可以做我所需要的。但是我不明白为什么枚举哈希表本身不返回键值对。实际上,它似乎返回了对象本身:
>     @{a=1; b=2} | %{ $_.gettype() }

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object

Powershell在这里做什么?

最佳答案

PowerShell管道将“展开”数组和集合(一级),但不会“散列”哈希表。如果要枚举PowerShell中哈希表的键/值对,请调用.getenumerator()方法:

$ht = @{a=1;b=2}
$ht.GetEnumerator()



Name Value
---- -----
a 1
b 2

关于powershell - Powershell与管道中的可枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14971263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com