如何在 PowerShell 中创建字典?


在 PowerShell 中创建字典,我们需要使用来自 .Net 命名空间 System.Collections.Generic.Dictionary 类。它具有 TKeyTValue。其基本语法为

Dictionary<TKey,TValue>

要了解更多关于此 .Net 命名空间的信息,请查看以下链接。

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0

要创建字典,我们首先将使用数据类型为字典对象类创建对象。在下面的示例中,我们需要添加国家名称和国家代码。因此,我们需要 StringInt。

$countrydata = New-Object System.Collections.Generic.Dictionary"[String,Int]"

一旦我们检查 $countrydata 变量的类型,它应该就是字典。例如,

示例

PS C:\> $Countrydata.GetType() | ft -AutoSize

输出

IsPublic IsSerial Name         BaseType
-------- -------- ----         --------
True     True     Dictionary`2 System.Object

让我们检查一下哪些方法可用。

示例

PS C:\> $Countrydata | Get-Member -MemberType Method | Select Name, Membertype

输出

Name              MemberType
----              ----------
Add                   Method
Clear                 Method
Contains              Method
ContainsKey           Method
ContainsValue         Method
CopyTo                Method
EnsureCapacity        Method
Equals                Method
GetEnumerator         Method
GetHashCode           Method
GetObjectData         Method
GetType               Method
OnDeserialization     Method
Remove                Method
ToString              Method
TrimExcess            Method
TryAdd                Method
TryGetValue           Method

因此,我们可以使用 Add() 方法插入成员。

示例

PS C:\> $Countrydata.Add("India",91)
PS C:\> $Countrydata.Add("Algeria",213)

一旦你检查值,它的输出应该以键值对的形式呈现。

示例

PS C:\> $Countrydata

输出

Key     Value
---     -----
India      91
Algeria   213

通常,PowerShell 程序员不会使用字典,因为它语法不常见,并且倾向于使用哈希表,因为哈希表可以轻松创建。

更新于:2020-12-15

11K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.