Why variables should be assigned with “.Value” when using ByRef?

前端 未结 1 1856
迷失自我
迷失自我 2021-01-13 21:34

What is the difference between:

$A="Something"

and

$A.Value="Something"

I see that this i

相关标签:
1条回答
  • 2021-01-13 22:02

    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
    >> }
    

    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
    

    Which nets the following output.

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

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

    0 讨论(0)
提交回复
热议问题