PowerShell 中是否提供联合类型

2023-12-29

类型化数组就像$arrIntOnly = [Int[]]@(1, 2, 3)对于确保所有元素都是有效类型很有用,但是是否可以定义多种类型,例如$arrIntOrString = [[Int | String][]]@(1, "two", 3)?


PowerShell 可以not有联合数据类型,但您可以使用 PowerShell 的default数组,它们是[object[]]-类型化,因此可以包含以下元素any type:

# Note: @(...) around the array isn't strictly necessary.
$arrIntOrString = 1, 'two', 3

没有直接的方法limit允许哪些特定类型。

但是,您可以使用验证属性- 类型System.Management.Automation.ValidateScriptAttribute https://learn.microsoft.com/en-US/dotnet/api/System.Management.Automation.ValidateScriptAttribute在本例中 - 强制将元素限制为指定类型:

[ValidateScript({ $_ -is [int] -or $_ -is [string] })] $arrIntOrString = 1, 'two', 3

The above would enforce the specified types both on initial assignment and later modifications; e.g., the following attempt to later "add"[1] an element of a non-permitted type would fail:

# FAILS, because $true (of type [bool]) is neither an [int] nor [string]
$arrIntOrString += $true

不幸的是,错误消息有点晦涩:MetadataError: The variable cannot be validated because the value System.Object[] is not a valid value for the arrIntOrString variable.

请注意,此验证是公平的slow,假设有一个脚本块({ ... }) 必须执行对于每个元素.


您还可以将此技术应用于参数声明,其中在PowerShell(核心)7+允许您定义自定义错误消息:

Function Foo {
  param(
    # Note: Use of ErrorMessage requires PS 7+
    [ValidateScript({ $_ -is [int] -or $_ -is [string] }, ErrorMessage = 'Please pass an integer or a string.')]
    $IntOrString
  )
  $IntOrString
}

Foo -IntOrString 1.0 # Fails validation 

[1] Arrays are fixed-length data structures, so what PowerShell does when you "add" to an array with += is to create a new array behind the scenes, with the new element(s) appended. Efficiently extensible alternatives to arrays are the non-generic System.Collections.ArrayList https://learn.microsoft.com/en-US/dotnet/api/System.Collections.ArrayList type (e.g., [System.Collections.ArrayList] (1, 'two', 3)) and the generic System.Collections.Generic.List`1 https://learn.microsoft.com/en-US/dotnet/api/System.Collections.Generic.List-1 type (e.g., [System.Collections.Generic.List[object]] (1, 'two', 3)). Then use the .Add() method to add to these collections; note that the ArrayList.Add() method returns a value, which you can suppress with $null = .... To initialize an empty collection of either type, cast @() to the type literal or call its static ::new() method.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PowerShell 中是否提供联合类型 的相关文章

随机推荐

  • java.lang.ClassNotFoundException:javax.ws.rs.client.RxInvokerProvider

    我尝试使用 loginServlet 从 jsp 页面登录 它重定向到 servlet 但不进行身份验证并引发错误 这是代码 JSP 文件 div class container div class row div class box di
  • Powershell:如何将结果添加到数组(ForEach-Object -Parallel)

    我知道 用参数 using foo我可以在运行时使用来自不同运行空间的变量ForEach Object Parallel在 Powershell 7 及更高版本中 但是如何将结果添加回变量呢 常用参数 and using 不管用 例如 Al
  • 如何向 pandas 数据框添加额外的行[重复]

    这个问题在这里已经有答案了 如果我有一个空数据框 columns Date Name Action ID df pd DataFrame columns columns 有没有办法向这个新创建的数据框追加新行 目前我必须创建一个字典 填充它
  • 我可以从网格生成点云吗? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在尝试从网格生成点云数据 例如 Maya 的 obj 文件 但是 我只能在互联网上找到相反的情况
  • 我如何给此列表中的每个人加薪

    需要使用 for each 循环 每个人获得的加薪是 1000 会是这样吗 int raise 1000 for Person i people people add raise i 我正在处理这个 public ArrayList
  • C 中的多字节整数变量[重复]

    这个问题在这里已经有答案了 我想知道如何计算单引号中字符串的整数值 我的示例代码是 include
  • 在Python中,导入类与导入类的模块有什么优缺点?

    我正在为大约 30 名开发人员组成的团队编写一套 Python 编码指南 作为我的文档的基础 到目前为止我已经研究了谷歌Python风格指南 http google styleguide googlecode com和PEP 8 风格指南
  • 我可以将对象保存到 app.config 文件中吗?

    我需要为我的应用程序使用一个配置文件 它将保存每个实体的详细信息列表 例如
  • 检查php会话是否不存在

    我有以下 php 代码 哪个应该检查会话是否不存在 如果不存在 则用户重定向 问题是这个条件始终为真 即使会话确实存在 我的问题是如何修复它 尝试用 SESSION like
  • 隐藏 UITableView 搜索栏

    我有一个 UITableViewController 它以标准方式设置了 UISearchDisplayController 搜索栏位于 tableView 内 我希望搜索栏一开始是隐藏的 真正隐藏 而不仅仅是滚动消失就像在这个解决方案中一
  • 在 Haskell 中过滤斐波那契数列

    我正在尝试过滤包含斐波那契数字的列表 我需要的只是奇数 并且小于或等于N 这是我到目前为止所拥有的 fib n n 0 0 n 1 1 otherwise fib n 1 fib n 2 fibs n a a lt fib x x lt 1
  • NodeJS“readline”模块不输出提示

    使用 NodeJS 我试图制作一个 笔记 管理器只是为了好玩 但是当我尝试使用 readline question 来获取用户关于他们想要做什么的输入 即创建一个新笔记 删除一个笔记 则不会显示提示 关于如何解决这个问题有什么建议吗 项目链
  • 在堆栈上分配大于页面大小的缓冲区会损坏内存吗?

    在Windows中 堆栈的实现方式如下 指定的页面后面是提交的堆栈页面 它的保护标志受到保护 因此 当 thead 引用受保护页面上的地址时 会出现内存错误 这使得内存管理器将受保护页面提交到堆栈并清除该页面的受保护标志 然后保留一个新页面
  • Flask-restful 在同一个类中具有 get/ 和 post 与 json

    如果 api add resource User user 则用户的 get 方法有效 该行未注释 另一个 api add resource 是 反之亦然 使 post 方法起作用 我怎样才能让这两条路径都起作用 from flask im
  • 处理命令行参数时清理控制流 [C#]

    我正在处理一个基于命令行参数执行大量 if else 分支的程序 这是 C 语言 但我确信它也适用于 Java C 等 以下是总体概述 if args Length 0 do something if args Length gt 0 ar
  • 无法远程访问9200端口

    刚刚开始使用elasticsearch 5 4 0 首先我将其安装在Mac 本地 上 然后安装在服务器上 在 Mac 中 当我在浏览器中运行 http 本地主机 9200 http localhost 9200 它向我显示输出 name N
  • Json解析Python子进程

    这是代码 inputDomain subprocess Popen cat etc localdomains shell True stdout subprocess PIPE domains inputDomain stdout read
  • 对话框打开时布局混乱

    我面临着一个非常奇怪的错误 其中一个布局的父级是 ConstraintLayout 当对话框打开时 后面的布局会自动开始收缩和移动 请参阅随附的 gif 来了解有关该错误的信息 请检查我的代码 看看我是否做错了什么 这是我的布局
  • 如何动态设置UIScrollView的内容大小

    我有关于UIScrollview 故事是我有一个UIView名为 ChartsView 我通过重写方法自己重新绘制它drawRect 绘图的内容是动态生成的 所以直到运行时我才知道它的大小 问题是如何 在哪里可以动态设置其超级视图 scro
  • PowerShell 中是否提供联合类型

    类型化数组就像 arrIntOnly Int 1 2 3 对于确保所有元素都是有效类型很有用 但是是否可以定义多种类型 例如 arrIntOrString Int String 1 two 3 PowerShell 可以not有联合数据类型