powershell - 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。)
谢谢!
解决方案
要添加到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()
。
推荐阅读
- python - 如何使用 selenium 和 python 从网页中获取可读文本
- c++ - 与字符连接时字符串连接不起作用
- node.js - 错误:没有匹配函数调用 'v8::Object::Set(v8::Local
- python - 如何在python中合并两个不相等的嵌套列表?
- postgresql - 将传入的文本时间戳从 rsyslog 转换为 postrgesql 的时间戳
- sharepoint - 如何使用 SPServices 和 JavaScript 更新 SharePoint 库子文件夹中的列表项
- python - 降低时间序列数据 x 轴的时间频率
- jenkins - Jenkins:如何永远保持升级版本?(请不要关闭)
- java - Xpath 替换 / Selenium Java
- prolog - 将列表从 findall 谓词转换为字符串序言