分配给 $null 的对象属性不会为 $null 测试为真 [英] Object-Property assigned $null does not test true for $null
问题描述
我已经开始使用 PowerShell 来完成一些事情,并在 PowerShell 中使用变量 $null
.
I've started using PowerShell to get some things done and played with the variable $null
in PowerShell.
我遇到的问题是,当我将变量 $null
分配给类中定义的变量时,测试返回 false
而不是 true代码>.
I've encountered the problem that when I assign the variable $null
to a variable defined in a class, the test returns false
not true
.
示例代码:
class test {
[string]$test1
}
$test = [test]::new()
$test.test1 = $null
$null -eq $test2 # tests true
$null -eq $test.test1 # tests false
现在对未定义变量 $test2
的测试返回 true
,因为 PowerShell 中的每个未定义变量都被分配了 $null
.
Now the test of the undefinded variable $test2
returns true
as every undefined variable in PowerShell is assigned $null
.
但是如果我测试对象 test
的属性 test1
,我分配了 $null
测试 false
$null
But if I test the property test1
of the object test
which I assigned $null
tests false
for $null
是不是因为在 PowerShell 中 $null
是一个值为 $null
的对象,而现在对象的属性不是 $null
因为它有对象 $null
分配给它的空值?
Is it because in PowerShell $null
is an object with the value $null
and now the property of the object is not $null
as it has the object $null
assigned to it with an empty value?
我已阅读 Microsoft 的文档 关于 $null 你想知道的一切",但它并没有启发我.
I've read into the docs of Microsoft "Everything you wanted to know about $null", but it does not enlighten me.
如果我不初始化变量,那么它会为 $null
测试 true
.
If I do not initialize the variable, then it will test true
for $null
.
推荐答案
$test.test1
不是 $null
,它是空字符串(因为你明确定义了它的值成为 [string]
):
$test.test1
is not $null
, it's empty string (because you explicitely defined it's value to be [string]
):
C:\> $test.test1.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
证明:
C:\> $test.test1 -eq ""
True
这篇关于分配给 $null 的对象属性不会为 $null 测试为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!