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

查看:74
本文介绍了布尔变量作为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'.

您可以通过将其重定向到$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天全站免登陆