在Powershell中通过引用传递字符串? [英] Pass strings by reference in Powershell?

查看:62
本文介绍了在Powershell中通过引用传递字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过引用将字符串传递给父作用域?

How can I pass strings by reference to the parent scope?

这不起作用,因为字符串是不可接受的值".

This doesn't work since strings are not acceptable "values".

function Submit([ref]$firstName){ 
    $firstName.value =  $txtFirstName.Text 
}

$firstName = $null
Submit([ref]$firstName)
$firstName

错误::在此对象上找不到属性'值;请确保它存在并且可设置"

Error: "Property 'value' cannot be found on this object; make sure it exists and is settable"

执行此操作不会产生错误,但也不会更改变量:

Doing this doesn't give an error but it doesn't change the variable either:

$firstName = "nothing"

function Submit([ref]$firstName){ 
    $firstName =  $txtFirstName.Text 
} 

Submit([ref]$firstName)
$firstName

单独执行第一个代码块是可行的.但是,当尝试在我的脚本中执行此操作时,它将再次返回错误.我已经对其进行了足够的修复,以使其可以分配变量并执行我想要的操作,但是它仍然引发错误,我想知道如何解决该问题.我认为这是因为它不喜欢变量;它在运行会话期间发生变化.这是我的脚本的链接

Doing the first code block by itself works. However when trying to do it in my script it returns the error again. I fixed it enough for it to assign the variable and do what I want but it still throws up an error and I was wondering how to fix that. I think it's because it doesn't like variable;es changing during a running session. Here is a link to my script

https://github.com/InconspicuousIntern/Form/blob/master/Form.ps1

推荐答案

您的第一个代码段在概念上是正确的,并且可以按预期工作-它本身不会产生 无法在此对象上找到属性值"".

Your first snippet is conceptually correct and works as intended - by itself it does not produce the "Property 'Value' cannot be found on this object" error.

由于以下行,您仅在链接到的完整脚本中看到错误:

You're seeing the error only as part of the full script you link to, because of the following line:

$btnSubmit.Add_Click({ Submit })

此行使您的 Submit 函数被调用为不带参数,这又导致 $ firstName 参数值成为$ null ,当您将其分配给 $ firstName.Value 时,这又导致上面引用的错误.

This line causes your Submit function to be called without arguments, which in turn causes the $firstName parameter value to be $null, which in turn causes the error quoted above when you assign to $firstName.Value.

相反,如您的第一个代码段中所述,对 Submit 的以下调用是正确的:

By contrast, the following invocation of Submit, as in your first snippet, is correct:

Submit ([ref] $firstName)  # Note the recommended space after 'Submit' - see below.

[ref] $ firstName 创建对调用方 $ firstName 变量的(临时)引用,该引用位于 Submit code>绑定到(本地)参数变量 $ firstName (这两个名称可能相同,但不一定,最好不要具有相同的名称),其中, $ firstName然后可以使用.Value 修改调用方的 $ firstName 变量.

[ref] $firstName creates a (transient) reference to the caller's $firstName variable, which inside Submit binds to (local) parameter variable $firstName (the two may, but needn't and perhaps better not have the same name), where $firstName.Value can then be used to modify the caller's $firstName variable.

语法注释:我故意在 Submit ([ref] $ firstName)之间放置一个空格,以使内容更清楚:

Syntax note: I've intentionally placed a space between Submit and ([ref] $firstName) to make one thing clearer:

此处的(...)(括号)不会将整个参数 list 括起来,就像在 method 调用中那样,它们包含单个参数 [ref] $ firstName -的必要性,因为否则 expression 不会被这样识别.

The (...) (parentheses) here do not enclose the entire argument list, as they would in a method call, they enclose the single argument [ref] $firstName - of necessity, because that expression wouldn't be recognized as such otherwise.

函数调用以所谓的 argument模式进行解析,其语法更类似于调用控制台应用程序的语法:参数以空格分隔,并且通常仅如果它们包含特殊字符,则需要引用.

Function calls in PowerShell are parsed in so-called argument mode, whose syntax is more like that of invoking console applications: arguments are space-separated, and generally only need quoting if they contain special characters.

例如,如果您还想将字符串'foo'作为第二个位置参数传递给 Submit :

For instance, if you also wanted to pass string 'foo', as the 2nd positional parameter, to Submit:

Submit ([ref] $firstName) foo

请注意两个参数之间如何用空格分隔,以及 foo 不需要用引号引起来.

Note how the two arguments are space-separated and how foo needn't be quoted.

关于替代方法:

[ref] 的主要目的是启用具有 ref / out 参数的.NET方法调用,并且如上所述,使用 [ref] 并非易事.

[ref]'s primary purpose is to enable .NET method calls that have ref / out parameters, and, as shown above, using [ref] is nontrivial.

对于调用PowerShell函数,通常有更简单的解决方案.

For calls to PowerShell functions there are generally simpler solutions.

例如,您可以将自定义对象传递给函数,并让该函数使用要返回的值更新其属性,这自然允许多个值被归还";例如:

For instance, you can pass a custom object to your function and let the function update its properties with the values you want to return, which naturally allows multiple values to be "returned"; e.g.:

function Submit($outObj){ 
    $outObj.firstName = 'a first name'
}

# Initialize the custom object that will receive values inside
# the Submit function.
$obj = [pscustomobject] @{ firstName = $null }

# Pass the custom object to Submit.
# Since a custom object is a reference type, a *reference* to it
# is bound to the $outObj parameter variable.
Submit $obj

$obj.firstName # -> 'a first name'

或者,您可以让 Submit 构造自定义对象本身,然后简单地 output 它:

Alternatively, you can just let Submit construct the custom object itself, and simply output it:

function Submit { 
    # Construct and (implicitly) output a custom
    # object with all values of interest.
    [pscustomobject] @{ 
        firstName = 'a first name' 
    } 
}

$obj = Submit

$obj.firstName # -> 'a first name'

这篇关于在Powershell中通过引用传递字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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