我想检查给定的字典(
$Dictionary -is [System.Collections.IDictionary]
)是否区分大小写?
[HashTable]
,描述如下:$Dictionary = [system.collections.generic.dictionary[string,object]]::new()
,我可能会简单地这样做:$Dictionary.Comparer.Equals('A', 'a')
[Ordered]
字典,我不知道...有没有通用的方法来检查字典的
EqualityComparer
?如评论中所述,并回答您的问题:
有没有通用的方法来检查字典的
?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
}
}