【发布时间】:2026-01-17 06:35:01
【问题描述】:
问题
为什么$null + @{} 有效,而@{} + $null 无效;即使将 null 转换为哈希表 (@{} + ([hashtable]$null))。
示例代码
[hashtable]$a = @{demo1=1;demo2='two'}
[hashtable]$b = @{demo3=3;demo4='Ivy'}
[hashtable]$c = $null
#combining 2 hashtables creates 1 with both hashes properties (would error if any properties were common to both)
write-verbose 'a + b' -Verbose
($a + $b)
#combining a null hashtable with a non-null hashtable works
write-verbose 'c + a' -Verbose
($c + $a)
#combing 2 null hashtables is fine; even if we've not explicitly cast null as a hashtable
write-verbose 'c + null' -Verbose
($c + $null)
#however, combinging a hashtable with null (i.e. same as second test, only putting null as the right argument instead of the left, produces an error
write-verbose 'a + c' -Verbose
($a + $c)
输出
Name Value
---- -----
demo3 3
demo4 Ivy
demo1 1
demo2 two
VERBOSE: c + a
demo1 1
demo2 two
VERBOSE: c + d
VERBOSE: a + c
A hash table can only be added to another hash table.
At line:19 char:1
+ ($a + $c)
+ ~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : AddHashTableToNonHashTable
旁注
顺便说一句,这让我发现了这个对哈希表进行空合并操作的有用技巧:($c + @{})。例如($a + ($c + @{})) 避免了上面产生的错误/(($a + @{}) + ($c + @{})) 为我们提供了一种完全安全的方法来添加任何一个值都可能为空的哈希表。
【问题讨论】:
-
类型转换 $null 产生 $null:
([hashtable]$null) -eq $null是 True。$null + @{}是有效的,因为添加到 $null 没有任何限制。 -
啊;所以 null 是无类型的,即使强制转换。谢谢。有道理/奇怪的是不是我以前遇到过的情况。关于 C# 的相关答案:*.com/a/930155/361842
标签: powershell null hashtable powershell-5.0