配列、ハッシュテーブル、辞書を作成しますか? 質問する

配列、ハッシュテーブル、辞書を作成しますか? 質問する

配列、ハッシュテーブル、辞書を作成する適切な方法は何ですか?

$array = [System.Collections.ArrayList]@()

$array.GetType()ArrayList を返します。OK。

$hashtable = [System.Collections.Hashtable]

$hashtable.GetType()RuntimeType を返しますが、正常ではありません。

$dictionary = ? 

この .NET の方法を使用して辞書を作成する方法は?

辞書とハッシュテーブルの違いは何ですか? どちらをいつ使用すればよいのかわかりません。

ベストアンサー1

ちゃんとした方法 (つまり 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

おすすめ記事