PowerShell中,扩展方法,和猴子打补丁 [英] PowerShell, Extension Methods, and Monkey Patching

查看:319
本文介绍了PowerShell中,扩展方法,和猴子打补丁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在PowerShell中编写扩展方法是什么?或者在现有的类型像顶栓的新方法[字符串]住在运行时?

Is it possible to write extension method in PowerShell? or to bolt a new method on top of an existing type like [string] live at runtime?

推荐答案

我不知道的方式来修补与类型的扩展方法。但它肯定可以通过使用add-me​​mber cmdlet来修补对象

I don't know of a way to patch a type with an extension method. But it's certainly possible to patch an object via the add-member cmdlet

PS> $a = "foo"
PS> $a = add-member -in $a -memberType ScriptMethod -name Bar -value { $this + "bar" } -passthru
PS> $a.Foo()
foobar

修改解释完全和完全可读的PowerShell语法:)

EDIT Explain the completely and totally readable PowerShell Syntax :)

我爱PowerShell的,但它确实拿出神秘语法不时。

I love PowerShell but it really does come up with cryptic syntax from time to time.

  • - 在:这是短期的inputObject,基本上说,添加成员到本
  • 在 - memberType:有许多不同类型的值可以添加到包括方法,注意属性,code法等运行时的对象...查看获取帮助附加成员-full为完整列表
  • 在 - 中继:取,只是有一个成员加入到它的对象,并将其推下来的管道。如果没有这个标志的分配将分配和空管道 $ A
  • 分配呼叫基本上确保 $ A 现在有你添加的方法
  • "-in": This is short for inputObject and essentially says add member to this
  • "-memberType": There are many different types of values you can add to a runtime object including methods, note properties, code method, etc ... See "get-help add-member -full" for a complete list
  • "-passthru": Take the object that just had a member added to it and push it down the pipeline. Without this flag the assignment would be assigning and empty pipeline to $a.
  • The assignment call is basically ensuring that $a now has the method you added

这篇关于PowerShell中,扩展方法,和猴子打补丁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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