在 Powershell 中传递引用类型参数 [英] Passing Reference Type Parameter in Powershell

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

问题描述

 function test1{
     param([System.Collections.ArrayList]$x
     )
     $x.Add("Test1Add")
     write "in Test1 $x"
 }
$x=New-Object System.Collections.ArrayList

这是我的代码,在我运行 test1 后,结果将是:

Here is my code , after I run test1, Result would be:

PS C:\Windows> test1 $x
0
in Test1 Test1Add

PS C:\Windows> $x
Test1Add

我想知道为什么会发生这种情况,我猜在调用 test1 时,就像将引用类型的指针传递给 test1 一样,就像 C# 或其他语言一样?像 int 这样的值类型,我必须使用 $script:x 来更改 global scope 中的 x .提前致谢

I am wondering why this happens, I guess when invoke test1, It just like passing a pointer of a Reference type to test1, Just like C# or other language? Value type like int, I must use $script:x to change the x in the gloabl scope . Thanks in advance

推荐答案

使用 参考变量:

  $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

编辑

我误解了这个问题,你想要相反的.结果与上述情况相同,但对于值类型则不同.如果您希望上述函数不更改引用的对象,则需要在函数内克隆它.可能有一个 Clone 函数,但在某些情况下,您必须手动创建克隆.在这种情况下,有这样的方法,因此您可以在上述函数的开头添加 $x=$x.Clone() 以获得所需的结果.

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.

值类型作为值传递,其他东西作为引用传递.检查 var 是否为 ValueType 的最简单方法是执行 $var.GetType().IsValueType.

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.

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

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