gpt4 book ai didi

powershell - 分配给 $null 的对象属性不会为 $null 测试为真

转载 作者:行者123 更新时间:2023-12-03 23:26:18 27 4
gpt4 key购买 nike

我已经开始使用 PowerShell 来完成一些事情并使用变量 $null在 PowerShell 中。
我在给变量赋值时遇到了问题$null对于类中定义的变量,测试返回 false不是 true .
示例代码:

class test {
[string]$test1
}

$test = [test]::new()

$test.test1 = $null

$null -eq $test2 # tests true

$null -eq $test.test1 # tests false
现在测试 undefined variable $test2返回 true因为 PowerShell 中的每个 undefined variable 都被分配了 $null .
但是如果我测试属性 test1对象 test我分配的 $null测试 false$null是不是因为在 PowerShell 中 $null是一个值为 $null 的对象现在对象的属性不是 $null因为它有对象 $null用空值分配给它?
我已阅读 Microsoft "Everything you wanted to know about $null" 的文档,但它并没有启发我。
如果我不初始化变量,那么它会测试 true$null .

最佳答案

$test.test1不是 $null ,它是空字符串(因为你明确定义它的值为 [string] ):

C:\> $test.test1.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
证明:
C:\> $test.test1 -eq ""
True

关于powershell - 分配给 $null 的对象属性不会为 $null 测试为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65322081/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com