Return Keyword in PowerShell

Return Keyword in PowerShell

https://info.sapien.com/index.php/scripting/scripting-classes/using-the-return-keyword-in-powershell-classes

In Standard PowerShell
the Return keyword exits the current scope. Return also returns the associated object . 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.
在这里插入图片描述

In Classes
The Return keyword works very differently in methods in PowerShell classes. It works like the Return statements in other languages, including C#.

In a class method, the Return keyword:

  • Exits the current scope.
  • Returns the associated object (return ).
  • Returns ONLY the associated object. It prevents the method from returning anything else.
  • The object that Return returns must match the return type of the method.
    • A return statement with no return type is a syntax error.
    • A return type with no return statement is a syntax error.
    • Returning a different type from the return statement is a runtime error.

在这里插入图片描述

If you would like to display a message within your function, beginning in PowerShell 5.0, you can use the Information stream. The code below corrects the above example using the Write-Information cmdlet with a InformationAction of Continue.
在这里插入图片描述

So, the Return keyword behaves very differently in classes than it does in standard PowerShell.

When PowerShell was being developed, the team wanted to make it very simple to use and they thought that the standard Return was easier. But, it was so confusing to people who know Return from other languages, that they realized they had made a mistake. The implementation in classes is an attempt to rectify that mistake.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值