函数输出类型

Function OutputType

OutputType 属性如何工作?

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

  return $a
}

$one = test 1
$two = test 0

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

我预计 $one 是真的,$two 是假的。

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

如概念性 about_Functions_OutputTypeAttribute 帮助主题所示:

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

    • PowerShell 提供 no 方式来声明强制的“return 类型” 语言这样的方式正如 C# 所做的那样:虽然限制和记录函数或脚本输出的内容 ("returns") 是有意义的,但在技术上可以自由输出任意数量、任意类型的对象,只需写入成功output stream.

    • 相比之下,可以强制执行input[=66=的数据类型]提供给函数或脚本,即由type-constraining其参数定义;例如,您可以通过将 param($a) 替换为 param([bool] $a) 来确保传递给 -a 参数的参数首先是布尔值,正如 Abraham 指出的那样 - 请参阅概念性 about_Functions_Advanced_Parameters 帮助主题。

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

    • 它将 元数据 添加到列出输出类型的函数定义中,PowerShell 的帮助系统和 tab-completion 等功能可以使使用.

    • 由函数/脚本作者来确保通过 [OutputType()] 列出的类型反映 实际输出数据类型.

      • 因此,信息可能不正确 - 就像您的情况一样,是不小心造成的。

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

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
}