为什么变量应该用“.Value"赋值?什么时候使用 ByRef? [英] Why variables should be assigned with ".Value" when using ByRef?

查看:39
本文介绍了为什么变量应该用“.Value"赋值?什么时候使用 ByRef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

$A="Something"

$A.Value="Something"

我发现这仅在使用 .Value 时有效:

I see that this is working only when .Value is used:

function main
{
    $A="Original A"
    $B="Original B"

    SetByRef1 ([ref]$A)
    SetByRef2 ([ref]$B)

    $A
    $B

    #output: Changed A
    #output: Original B
}


function SetByRef1([ref]$A)
{
    $A.Value = "Changed A"
}

function SetByRef2([ref]$B)
{
    $B = "Changed B"
}

main

我猜,$B = "Changed B" 正在定义一个新变量 B,而 $A.Value = "Changed A" 只是在改变内容,但我还没有找到确认.

I guess, that $B = "Changed B" is defining a new variable B, whereas $A.Value = "Changed A" is just changing the content but I haven't found a confirmation for that.

推荐答案

在函数中使用引用变量时,您必须使用 .Value 与原始对象交互,如 About_Ref

When using reference variables in functions you must use the .Value to interact with the original object as seen in About_Ref

PS C:\ps-test> function double
>> {
>>     param ([ref]$x) $x.value = $x.value * 2
>> }

如果您在函数内部检查对象,您可以看到不同之处.在函数 SetByRef1 中,我添加了以下几行.

If you examine the object while inside the function you can sort of see the difference. Inside the function SetByRef1 I added the following lines.

$a.GetType().FullName
$a.value.GetType().FullName

生成以下输出.

System.Management.Automation.PSReference`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
System.String

$a.value 的类型表明您正在对原始对象进行操作.

The type of $a.value shows that you are acting on the original object.

这篇关于为什么变量应该用“.Value"赋值?什么时候使用 ByRef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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