Passing Reference Type Parameter in Powershell

前端 未结 1 545
难免孤独
难免孤独 2021-01-28 07:44
 function test1{
     param([System.Collections.ArrayList]$x
     )
     $x.Add(\"Test1Add\")
     write \"in Test1 $x\"
 }
$x=New-Object System.Collections.ArrayList
         


        
1条回答
  •  故里飘歌
    2021-01-28 08:10

    Use Reference variables:

      $x=New-Object System.Collections.ArrayList
      function test( [ref][System.Collections.ArrayList]$x) { $x.value.Add($(get-random)) }
      test ([ref]$x)
      test ([ref]$x)
      $x
    

    EDIT

    I misunderstood the question, you wanted the opposite. The result is the same in above case but not for value types. If you want above function not to change the referenced object you need to clone it inside the function. There may be a Clone function, but in some cases you will have to manually create the clone. In this case there is such method so you can add $x=$x.Clone() at the start of the above function to get the desired result.

    Value types are passed as value and other things are passed as reference. The easiest way to check if var is of ValueType is to do $var.GetType().IsValueType.

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