powershell有method_missing()吗?
我一直在研究 powershell 的动态功能,我想知道
powershell 中是否有类似于 Ruby 的 method_missing() 的东西,您可以在其中设置“捕获所有方法”来动态处理对您的计算机上不存在的方法的调用物体?
I have been playing around with the dynamic abilities of powershell and I was wondering something
Is there is anything in powershell analogous to Ruby's method_missing() where you can set up a 'catch all method' to dynamically handle calls to non-existant methods on your objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,不是真的。我怀疑下一版本的 PowerShell 将更加符合 .NET 4 中添加的动态调度功能,但目前,这在纯 PowerShell 中是不可能的。
尽管我确实记得有一个类似于 .NET 的 TypeDescriptor 中的组件模型,用于创建动态向 PowerShell 提供属性和方法的对象。例如,这就是如何将 XML 元素视为对象。但是,这根本没有记录,而且根据我的经验,集成所需的许多类型/方法都被标记为内部。
No, not really. I suspect that the next version of PowerShell will become more in line with the dynamic dispatch capabilities added to .NET 4 but for the time being, this would not be possible in pure PowerShell.
Although I do recall that there is a component model similar to that found in .NET's TypeDescriptor for creating objects that provide properties and methods dynamically to PowerShell. This is how XML elements are able to be treated like objects, for example. But this is poorly documented if at all and in my experience, a lot of the types/methods needed to integrate are marked as internal.
你可以模仿它,但这很棘手。该技术在 Lee Holmes 的书中进行了描述,可归结为两个脚本 - Add-RelativePathCapture http://poshcode.org/2131< /a> 和 New-CommandWrapper http://poshcode.org/2197。
本质是 - 您可以通过 New-CommandWrapper 覆盖任何 cmdlet。因此,您可以重新定义几乎每个命令末尾隐式调用的 Out-Default(不包括末尾带有显式格式化程序(如 Format-Table)的命令)。在新的 Out-Default 中,您检查最后一个命令是否抛出异常,表示未找到方法/属性。然后您插入 method_missing 逻辑。
You can emulate it, but it's tricky. The technique is described in Lee Holmes book and is boiled down to two scripts - Add-RelativePathCapture http://poshcode.org/2131 and New-CommandWrapper http://poshcode.org/2197.
The essence is - you can override any cmdlet via New-CommandWrapper. Thus you can redefine Out-Default that is implicitly invoked at the end of almost every command (excluding commands with explicit formatters like Format-Table at the end). In the new Out-Default you check if the last command threw an exception saying that no method / property was found. And there you insert your method_missing logic.
您可以在 Powershell 2.0 中使用 Try Catch
http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/11/hey-scripting-guy-march-11-2010.aspx
You could use Try Catch within Powershell 2.0
http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/11/hey-scripting-guy-march-11-2010.aspx