Powershell“私有"范围似乎根本没有用 [英] Powershell "private" scope seems not useful at all

查看:28
本文介绍了Powershell“私有"范围似乎根本没有用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的脚本,来自互联网:

I've got the script below, from internet:

$private:a = 1
Function test  {
    "variable a contains $a"
    $a = 2
    "variable a contains $a"
}
test

它打印了 2.没问题.如果我删除私人",如下所示:

It prints 2. No problem. If I delete "private", like below:

$a = 1
Function test  {
    "variable a contains $a"
    $a = 2
    "variable a contains $a"
}

它仍然打印2".好像没什么区别.您能否提供一个关于私有"范围如何影响结果的快速示例?

Still it prints "2". Seems no difference. Could you provide an quick sample of how "private" scope affects the result?

谢谢.

推荐答案

在编写调用用户提供的回调的函数时,私有作用域非常有用.考虑这个简单的例子:

Private scope can be useful when writing a function that invokes a user-supplied callback. Consider this simple example:

filter Where-Name {
    param(
        [ScriptBlock]$Condition
    )
    $FirstName, $LastName = $_ -split ' '
    if(&$Condition $FirstName $LastName) {
        $_
    }
}

那么,如果有人这样称呼它:

Then, if someone calls it like this:

$FirstName = 'First2'
'First1 Last1', 'First2 Last2', 'First3 Last3' |
  Where-Name {param($a, $b) $a -eq $FirstName}

他们希望只看到 First2 Last2 行,但实际上这将打印所有三行.这是因为 $FirstName 变量发生冲突.为防止此类冲突,您可以将 Where-Name 中的变量声明为私有:

they'll expect to see only the First2 Last2 row, but actually this will print all three rows. This is because of a collision on the $FirstName variable. To prevent such collisions, you can declare variables in Where-Name as private:

filter Where-Name {
    param(
        [ScriptBlock]$private:Condition
    )
    $private:FirstName, $private:LastName = $_ -split ' '
    if(&$Condition $FirstName $LastName) {
        $_
    }
}

现在 Where-Name 中的 $FirstName 在从 $Condition<引用时不会在外部作用域中隐藏 $FirstName/code> 脚本块.

Now $FirstName in Where-Name does not hide $FirstName in the outer scope when referenced from the $Condition script block.

这篇关于Powershell“私有"范围似乎根本没有用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆