Powershell中具有元组键的字典

Powershell中具有元组键的字典,powershell,dictionary,tuples,Powershell,Dictionary,Tuples,我需要在Powershell中创建一个具有元组键的字典。 就像我在C#中所能做的那样: var test = new Dictionary<(int, bool), int>(); // Add test.Add((1, false), 5); // Get int a = test[(1, false)]; var test=newdictionary(); //加 测试。添加((1,错误),5); //得到 int a=测试[(1,假)]; (摘自) 可能吗?(我正在运行

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

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

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

// Get
int a = test[(1, false)];
var test=newdictionary();
//加
测试。添加((1,错误),5);
//得到
int a=测试[(1,假)];
(摘自)

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

谢谢

要补充To对这个问题的精彩评论:

以下是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)]
  • usingnamespace
    是一个类似于C#的
    usinging
    构造的PSv5+功能:它允许您仅通过名称引用指定名称空间中的类型,而无需名称空间限定

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

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

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

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

您可以在PowerShell(
$x=@{[System.ValueTuple]::create(1,$false)=5};$x[[System.ValueTuple]::create(1,$false)],
中显式创建一个
元组,但是,由于它没有语法上的甜点,而且PowerShell对泛型的支持有点参差不齐,所以这不是一个特别好的体验。我想您可以用一个简短的名称将
Create
封装在一个本地函数中。请注意,PowerShell自己的自定义对象在用作键时表现得“怪异”,因为PowerShell不会自动添加适当的哈希和相等支持,因此这些也不是很有吸引力的替代方案。谢谢@JeroenMostert,我会尝试一下!我认为关于哈希和相等支持的说明对我来说不会有问题,因为生成的命令将被发送到带有C#代码的API。哈希和相等支持始终是相关的,无论语言如何,因为
字典
(和
哈希表
,PowerShell使用它来查找和存储密钥
ValueTuple
对此有支持,因此它们适合作为字典键,但PowerShell的自定义对象不支持(无论如何,默认情况下不支持)。
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)]