检查字典是否区分大小写

问题描述 投票:0回答:1

我想检查给定的字典(

$Dictionary -is [System.Collections.IDictionary]
)是否区分大小写?

  • 对于
    [HashTable]
    ,描述如下:
    在 PowerShell 中区分不同类型的哈希表?
  • 对于
    $Dictionary = [system.collections.generic.dictionary[string,object]]::new()
    ,我可能会简单地这样做:
    $Dictionary.Comparer.Equals('A', 'a')
  • 但是对于例如一本
    [Ordered]
    字典,我不知道...

有没有通用的方法来检查字典的

EqualityComparer

或者:我如何涵盖所有字典风格?

powershell dictionary case-sensitive
1个回答
1
投票

如评论中所述,并回答您的问题:

有没有通用的方法来检查字典的

EqualityComparer

据我所知,没有,您可以尽力跟踪如何处理每个特定情况,有些可能是通过反射,如

Hashtable
OrderedDictionary
和一些可能通过公共属性,如
Dictionary<TKey, TValue>
和其他通用类型 但仅涵盖特定情况

我相信没有办法涵盖实现

IDictionary
IDictionary<TKey, TValue>
接口的所有类型。显然不建议使用反射方法,没有人向您保证这些私有字段或属性将来会发生变化

抛开这一点,下面的内容可能会帮助您更好地了解如何解决这个问题。

$supportedGenericTypes = @(
    # there is no interface ensuring that a type implementing `IDictionary<TKey, TValue>`
    # will have a `.Comparer` property, you will need to manually check if they actually do
    # before adding them to this list
    [System.Collections.Generic.Dictionary`2]
    [System.Collections.Concurrent.ConcurrentDictionary`2]
    [System.Collections.Generic.SortedDictionary`2]
)

[System.Collections.Generic.Dictionary[string, string]]::new(),
[ordered]@{},
@{},
[System.Collections.Concurrent.ConcurrentDictionary[string, string]]::new(),
[System.Collections.Generic.SortedDictionary[string, string]]::new() |
    ForEach-Object {
        $type = $_.GetType()
        if ($type.IsGenericType -and $type.GetGenericTypeDefinition() -in $supportedGenericTypes) {
            $comparer = $_.Comparer
            # need to cover any custom type implementing `IDicitonary<TKey, TValue>` here...
        }
        elseif (-not $type.IsGenericType) {
            $instance = $_

            switch ($type) {
                ([System.Collections.Hashtable]) {
                    $comparer = [System.Collections.Hashtable].
                        GetField('_keycomparer', [System.Reflection.BindingFlags] 'NonPublic,Instance').
                        GetValue($instance)
                }
                ([System.Collections.Specialized.OrderedDictionary]) {
                    $comparer = [System.Collections.Specialized.OrderedDictionary].
                        GetField('_comparer', [System.Reflection.BindingFlags] 'NonPublic,Instance').
                        GetValue($instance)
                }
                # need to cover any custom type implementing `IDicitonary` here...
            }
        }
        else {
            throw [System.NotImplementedException]::new()
        }

        [pscustomobject]@{
            Type     = $type
            Comparer = $comparer
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.