创建数组、哈希表和字典?
Create an array, hashtable and dictionary?
创建数组、哈希表和字典的正确方法是什么?
$array = [System.Collections.ArrayList]@()
$array.GetType()
returns ArrayList, OK.
$hashtable = [System.Collections.Hashtable]
$hashtable.GetType()
returns 运行时类型,不正确。
$dictionary = ?
如何使用这种 .NET 方式创建字典?
字典和哈希表有什么区别?我不确定什么时候应该使用其中之一。
正确的方式(即 PowerShell 方式)是:
数组:
> $a = @()
> $a.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
哈希表/字典:
> $h = @{}
> $h.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
以上对于大多数类似字典的场景应该足够了,但如果你确实明确想要来自 Systems.Collections.Generic
的类型,你可以像这样初始化:
> $d = New-Object 'system.collections.generic.dictionary[string,string]'
> $d.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Dictionary`2 System.Object
> $d["foo"] = "bar"
> $d | Format-Table -auto
Key Value
--- -----
foo bar
如果你想初始化一个数组你可以使用下面的代码:
$array = @() # empty array
$array2 = @('one', 'two', 'three') # array with 3 values
如果要初始化哈希表,请使用以下代码:
$hashtable = @{} # empty hashtable
$hashtable2 = @{One='one'; Two='two';Three='three'} # hashtable with 3 values
Powershell 中的哈希表和字典几乎相同,因此我建议几乎在所有情况下都使用哈希表(除非您需要在需要字典的 .NET 中执行某些操作)
创建数组、哈希表和字典的正确方法是什么?
$array = [System.Collections.ArrayList]@()
$array.GetType()
returns ArrayList, OK.
$hashtable = [System.Collections.Hashtable]
$hashtable.GetType()
returns 运行时类型,不正确。
$dictionary = ?
如何使用这种 .NET 方式创建字典?
字典和哈希表有什么区别?我不确定什么时候应该使用其中之一。
正确的方式(即 PowerShell 方式)是:
数组:
> $a = @()
> $a.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
哈希表/字典:
> $h = @{}
> $h.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
以上对于大多数类似字典的场景应该足够了,但如果你确实明确想要来自 Systems.Collections.Generic
的类型,你可以像这样初始化:
> $d = New-Object 'system.collections.generic.dictionary[string,string]'
> $d.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Dictionary`2 System.Object
> $d["foo"] = "bar"
> $d | Format-Table -auto
Key Value
--- -----
foo bar
如果你想初始化一个数组你可以使用下面的代码:
$array = @() # empty array
$array2 = @('one', 'two', 'three') # array with 3 values
如果要初始化哈希表,请使用以下代码:
$hashtable = @{} # empty hashtable
$hashtable2 = @{One='one'; Two='two';Three='three'} # hashtable with 3 values
Powershell 中的哈希表和字典几乎相同,因此我建议几乎在所有情况下都使用哈希表(除非您需要在需要字典的 .NET 中执行某些操作)