Powershell:引用数组中的单个元素

The*_*nis 6 arrays variables powershell reference

我想使用 [ref] 关键字引用数组中的单个元素。

如何测试参考:

$var1 = "this is a string"
[ref]$var2 = [ref]$var1

$var2.Value
this is a string

$var2.Value += " too!"
$var2.Value
this is a string too!

$var1
this is a string too!
Run Code Online (Sandbox Code Playgroud)

以上按预期工作。但是现在要引用任何数组中的单个元素?

$var3="string 1", "string 2", "string 3"
[ref]$var2=[ref]($var3[1])

$var2.Value
string 2

$var2.Value += " updated!"
$var2.Value
string 2 updated!

$var3[1]
string 2
Run Code Online (Sandbox Code Playgroud)

我希望$var3[1]返回与$var2.Value. 我究竟做错了什么?

mkl*_*nt0 3

In PowerShell, you cannot obtain a reference to individual elements of an array.

To gain write access to a specific element of an array, your only option is:

  • to use a reference to the array as a whole

  • and to reference the element of interest by index.

In other words:

Given $var3 = "string 1", "string 2", "string 3", the only way to modify the 2nd element of the array stored in $var3 is to use $var3[1] = ... (barring acrobatics via C# code compiled on demand).


As for what you tried:

[ref] $var2 = [ref] ($var3[1])

在 PowerShell 中,如果您获取的值$var3[1],它总是存储在的第二个元素中的数据的副本$var3(如果该元素包含值类型的实例,则可能是实际数据的副本,或者是引用类型实例的引用,否则)。

因此,将该副本强制转换到的位置[ref]总是与原始数组元素分离。