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] 来确保传递给
,正如亚伯拉罕所说 - 请参阅概念 about_Functions_Advanced_Parameters帮助主题。-a
参数的参数一开始就是 bool 值$a)
相反,
[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/