当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 避免在表达式中分配变量

作者:精品下载站 日期:2024-12-14 03:03:42 浏览:12 分类:玩电脑

避免在表达式中分配变量


PowerShell 允许您通过将赋值括在括号 () 中来在表达式中使用赋值。 PowerShell 传递分配的值。例如:

# In an `if` conditional
if ($foo = Get-Item $PROFILE) { "$foo exists" }

# Property access
($profileFile = Get-Item $PROFILE).LastWriteTime

# You can even *assign* to such expressions.
($profileFile = Get-Item $PROFILE).LastWriteTime = Get-Date

笔记

虽然允许使用此语法,但不鼓励使用它。在某些情况下,这不起作用,代码作者的意图可能会让其他代码审查者感到困惑。

局限性

分配案例并不总是有效。当它不起作用时,分配将被丢弃。如果您创建可变值类型的实例,并尝试将该实例保存在变量中并在同一表达式中修改其属性之一,则属性分配将被丢弃。

# create mutable value type
PS> Add-Type 'public struct Foo { public int x; }'

# Create an instance, store it in a variable, and try to modify its property.
# This assignment is effectively IGNORED.
PS> ($var = [Foo]::new()).x = 1
PS> $var.x
0

不同之处在于您无法返回对该值的引用。本质上, ($var=[Foo]::new()) 等价于 $ ($var=[Foo]::new(); $var)。您不再对变量执行成员访问,而是对变量的输出(即副本)执行成员访问。

解决方法是先创建实例并将其保存在变量中,然后通过变量分配给属性:

# create mutable value type
PS> Add-Type 'public struct Foo { public int x; }'

# Create an instance and store it in a variable first
# and then modify its property via the variable.
PS> $var = [Foo]::new()
PS> $var.x = 1
PS> $var.x
1

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯