布尔变量作为 Object[] 返回 [英] Boolean variable gets returned as an Object[]

查看:9
本文介绍了布尔变量作为 Object[] 返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回布尔变量的函数

I have a function which is returning a boolean variable

function test ($param1, $param2)
{
  [boolean]$match=$false;

  <# function logic #>

  return $match
}

当我尝试在变量 $retByFunct=testing $param1 $param 2 中捕获函数调用时

when I try and catch the function call in a variable $retByFunct=testing $param1 $param 2

我将 $retByFunct 作为对象数组.如果我尝试强制 $retByFunct 成为布尔变量,即 [boolean] $retByFunct=testing $param1 $param 2,我会收到以下错误.

I am getting $retByFunct as an Object Array. If I try and force the $retByFunct to be a boolean variable i.e. [boolean] $retByFunct=testing $param1 $param 2, I get the following error.

无法将值System.Object[]"转换为 System.Boolean 类型

Cannot convert value "System.Object[]" to type System.Boolean

我在返回之前检查了 $match.GetType().控制台说它是一个布尔值,所以我很困惑为什么在函数调用之后它被转换为一个对象数组.

I checked out $match.GetType() just before returning it. The console says its a boolean, so am confused as to why after function call its getting converted to an Object Array.

我知道某些集合对象会发生这种情况,并且有一种解决方法,但是如何处理变量的情况?

I am aware this happens for some collection objects and there is a work around for that, but how do I handle a case for a variable?

推荐答案

正如@mjolinor 所说,您需要显示其余代码.我怀疑它在某处的成功输出流上生成输出.PowerShell 函数在该流上返回 all 输出,而不仅仅是 return 关键字的参数.来自文档:

As @mjolinor said, you need to show the rest of your code. I suspect it's generating output on the success output stream somewhere. PowerShell functions return all output on that stream, not just the argument of the return keyword. From the documentation:

在 PowerShell 中,即使没有包含 Return 关键字的语句,每个语句的结果也会作为输出返回.C 或 C# 等语言仅返回由 return 关键字指定的一个或多个值.

In PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the return keyword.

没有区别

function Foo {
  'foo'
}

function Foo {
  'foo'
  return
}

function Foo {
  return 'foo'
}

上述每个函数在调用时都会返回字符串foo.

Each of the above functions returns the string foo when called.

附加输出导致返回值为数组,例如:

Additional output causes the returned value to be an array, e.g.:

function Foo {
  $v = 'bar'
  Write-Output 'foo'
  return $v
}

这个函数返回一个数组'foo', 'bar'.

This function returns an array 'foo', 'bar'.

您可以通过将其重定向到 $null 来抑制不需要的输出:

You can suppress undesired output by redirecting it to $null:

function Foo {
  $v = 'bar'
  Write-Output 'foo' | Out-Null
  Write-Output 'foo' >$null
  return $v
}

或通过在变量中捕获它:

or by capturing it in a variable:

function Foo {
  $v = 'bar'
  $captured = Write-Output 'foo'
  return $v
}

这篇关于布尔变量作为 Object[] 返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆