首页 > 解决方案 > Powershell中带有元组键的字典

问题描述

我需要在 Powershell 中创建一个带有元组键的字典。就像我在 C# 中可以做的那样:

var test = new Dictionary<(int, bool), int>();

// Add
test.Add((1, false), 5);

// Get
int a = test[(1, false)];

(取自Hashtable with MultiDimensional Key in C#

可能吗?(我正在运行 Powershell 版本 5.1.18362.145。)

谢谢!

标签: powershelldictionarytuples

解决方案


要添加到Jeroen Mostert对该问题的出色评论:

以下是您的 C# 代码到 PowerShell v5.1+ 代码的直接翻译:

using namespace System.Collections.Generic

# Construct
$test = [Dictionary[[ValueTuple[int, bool]], int]]::new()

# Add
$test.Add([ValueTuple[int, bool]]::new(1, $false), 5)

# Get
$test[[ValueTuple[int, bool]]::new(1, $false)]
  • using namespace是类似于 C#using构造的 PSv5+ 功能:它允许您仅通过名称来引用指定命名空间中的类型,而无需命名空间限定。

  • 正如 Jeroen 指出的那样,PowerShell 没有值元组实例的语法糖,因此 C# 元组文字(1, false)必须表示为显式构造函数调用:
    [ValueTuple[int, bool]]::new(1, $false)

    • Create另一种方法是在非泛型基类型上使用静态方法,在这种情况下推断System.ValueType元组组件类型:
      [ValueTuple]::Create(1, $false)

鉴于 PowerShell 通过::new()类型本身的静态方法公开类型的构造函数,您可以通过实例化特定元组类型一次并通过变量重用它来简化代码(忽略损坏的语法突出显示):

using namespace System.Collections.Generic

# Instantiate the concrete tuple type (type arguments locked in).
$tupleType = [ValueTuple[int, bool]]

# Construct the dictionary with the tuple type as the key.
# See explanation below.
$test = [Dictionary`2].MakeGenericType($tupleType, [int])::new()

#`# Add
$test.Add($tupleType::new(1, $false), 5)

# Get
$test[$tupleType::new(1, $false)]

缺点是字典构造变得更加笨拙,因为诸如此类的 PowerShell 类型文字[Dictionary[[ValueTuple[int, bool]], int]]不能有非文字组件。为了解决这个问题,System.Type.MakeGenericType用于从动态指定的类型参数构造封闭的泛型类型;注意需要指定调用`2的开放泛型类型的arity () .MakeGenericType()


推荐阅读