在 Powershell 中创建 .NET 数组类型

Making .NET array type in Powershell

我正在尝试 System.Memory[char] .

[System.Memory[char]]::Memory([char],0,10) 说找不到 System.Memory 类型 .

也尝试过

[System.Memory`3+[[char],0,10]]@()

解决:问题似乎是Powershell使用的.NET版本问题。

PowerShell v5 中引入的静态方法::new()提供访问权限类型的构造函数.[1]

# Initialize a [System.Memory[char]] instance with 10 NUL (0x0) chars,
# from a [char[]] array.
[System.Memory[char]]::new(
  [char[]]::new(10)
)

注意:两个System.Memory`1 constructors都需要一个[char[]]数组作为参数。 3 参数重载中的两个附加参数 startlength 必须引用该数组 .

中的元素范围

上面简单地创建了一个 10 元素的数组开始(隐式使用 NUL 个字符),避免了对额外参数的需要。

如果您希望输入数组使用 NUL 以外的给定字符,您可以使用 , [char] 'x' * 10:
, [char] 'x' 用 char 创建一个 single-element 数组。 'x',然后 * 10 复制到 return 一个 10 元素数组。请注意,数组将是 [object[]] 类型,而不是 [char[]] 类型,但它仍然有效。


注:

  • [System.Memory[char]]@() 工作,因为为了让 PowerShell 将此转换转换为 single-parameter 构造函数调用,操作数必须是 [char[]] 数组:

    • [System.Memory[char]] [char[]] @()
  • 从根本上说,System.Memory`1 类型仅在 .NET Core 2.1+ / .NET 5+[= 中可用86=].

    • 检查类型在您的 PowerShell 会话中是否可用的最简单方法是 [bool] $IsCoreClr returns $true - 换句话说:您需要是 运行 PowerShell (Core) 7+,现代 cross-platform,install-on-demand 版本的 PowerShell。

[1] 在早期的 PowerShell 版本中,您需要使用 method/constructor 调用中熟悉的 New-Object cmdlet, which uses argument(-parsing) mode, as all cmdlets do. As such, its syntax doesn't map cleanly onto the expression-mode 语法,尤其是在传递单个参数是一个数组,如本例所示:
New-Object System.Memory[char] -ArgumentList (, (New-Object char[] 10))
注意需要将 , [char] 0) * 10 构造的数组包裹在 另一个 数组中,即使 New-Object 处理原始数组所需的临时数组数组作为目标构造函数的 单个 参数。
此外,::new() 表现更好,尽管这通常无关紧要。有关详细信息,请参阅