powershell - 函数输出类型

标签 powershell

OutputType 属性如何工作?

function test
{
  [OutputType([Bool])]
  Param ($a)

  return $a
}

$one = test 1
$two = test 0

$one.GetType() # Int32
$two.GetType() # Int32

我预计 $one 为 true,$two 为 false。

最佳答案

Abraham Zinala 的有用评论为基础和 Mike Shepard :

作为概念about_Functions_OutputTypeAttribute帮助主题表示:

  • [OutputType()] 属性控制函数或脚本的实际输出数据类型

    • PowerShell 没有提供像 C# 等语言那样声明强制“返回类型”的方法:尽管限制和记录返回类型是有意义的。函数或脚本输出(“返回”),技术上可以自由地输出任意数量、任意类型的对象,只需写入成功 output stream .

    • 相比之下,可以强制执行提供给函数或脚本的输入的数据类型,即通过对其参数定义进行类型约束;例如,您可以通过将 param($a) 替换为 param([bool] 来确保传递给 -a 参数的参数一开始就是 bool 值$a),正如亚伯拉罕所说 - 请参阅概念 about_Functions_Advanced_Parameters帮助主题。

  • 相反,[OutputType()] 属性仅具有信息字符:

    • 它将元数据添加到列出输出类型的函数定义中,可以利用 PowerShell 的帮助系统和制表符补全等功能。

    • 函数/脚本作者有责任确保通过[OutputType()]列出的类型反射(reflect)实际输出数据类型

      • 因此,该信息可能不正确 - 就像您的情况一样,是无意的。

因此,您的函数需要确保所需的数据类型作为输出语句的一部分输出:

function test
{
  [OutputType([bool])]
  Param ($a) # $a is allowed to be of any type (no type constraint present)

  # Output a [bool] explicitly.
  # Note: No strict need for `return` here, 
  #       thanks to PowerShell's implicit output behavior.
  [bool] $a
}

关于powershell - 函数输出类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72005536/

相关文章:

powershell - 如何创建 Windows 安装程序

powershell - 使用 UniqueKeyContainerName 获取证书绝对路径

c# - 在使用 PowerShell 创建新邮箱期间设置 Active Directory 帐户属性

iis - 使用 Powershell 更改 IIS 站点主目录

windows - 使用 "-noprofile"参数提升当前脚本

powershell - 不确定Get-ChildItem结果格式

powershell - GetDate 为负 30 分钟并以 UTC 格式显示

powershell - 将用户/计算机的OU添加到安全组

csv - 基于 CSV 内容的 Powershell 复制文件

powershell - 如何在powershell中使用system.tuple?