【问题标题】:PowerShell - why does looking up an array in a Hashtable return an empty array?PowerShell - 为什么在 Hashtable 中查找数组会返回一个空数组?
【发布时间】:2017-06-24 03:14:27
【问题描述】:

我在寻找其他东西时遇到了这个问题,因此除了对这个示例感到困惑之外,没有更广泛的代码或目的:

$H = @{}                 # new, empty hashtable

                         # String test - lookup fails, hashtable returns $null
$H["test"].GetType()     # "You cannot call a method on a null-valued expression."


                         # Array test - should do the same
$Key = @('a','b')              
$H[$Key].GetType()       # Object[]  what?? Where did this come from? <--<<====<<====<<
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


                         # Double check that ..
$H.ContainsKey($Key)     # False. Doesn't contain the key(!)

$H.Values.Count          # 0. It's empty. As it should be. 

当键是数组时,对 empty 哈希表的查找如何(为什么)返回 object[],而不是其他情况?

注意。我知道您不能/不应该将数组用作哈希表键,至少部分原因是数组不相等,除非它们是内存中的同一个对象,例如array/object keys for hashtables in powershell;但是数组确实有.GetHashCode() - 无论它们的键是什么,它不应该仍然为失败的查找返回 $null 吗?

在 Windows/PSv4 和 Linux/PS6-alpha 上发生

Here 是 this[Object key] 的 CoreCLR Hashtable 源,尽管我无法做出任何相关的事情。也许这是在更高级别的 PowerShell 哈希表处理中(我还没有找到)。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    这是 PowerShell 功能,允许您在索引集合时指定索引数组:

    $Array = 10..1
    $Indexes = 1, 3, 5
    $Array[$Indexes] # 9, 7, 5
    
    $Hash = @{
        a = 1
        b = 2
        c = 3
    }
    $Indexes = 'c', 'f', 'a'
    $Hash[$Indexes] # 3, $null, 1
                    # System.Collections.Hashtable designed to return null,
                    # when asking not existing key.
    
    $String = 'abcdefghijklmnopqrstuvwxyz'
    $Indexes = 7, 4, 11, 11, 14
    $String[$Indexes] # h, e, l, l, o
    

    如果你真的想通过数组索引哈希表作为单个对象,那么你可以使用Item参数化属性:

    $Array = 1..10
    $Hash = @{ $Array = 'Value' }
    $Hash.Item($Array)
    

    【讨论】:

    • "如果你真的想通过数组作为单个对象索引哈希表" - 我认为我真正想要的行为是 Python 元组 ('a','b') -> [System.Tuple]::Create('a','b') -但那是另一回事。这回答了我的问题,解释了它,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 2011-06-24
    • 2017-11-13
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多