groovy有像C#中的扩展方法吗?

Mus*_*afa 12 groovy extension-methods

我可以在C#中以某种方式向最终类添加方法吗?

所以我可以这样做:

"Some text".myOwnFunction();
Run Code Online (Sandbox Code Playgroud)

代替:

MyStaticClass.myOwnFunction("Some text");
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 20

您可以通过metaClass将其添加到所有将来的字符串实例中

    String.metaClass.myOwnFunction = {-> delegate.length() }
    assert "Tim".myOwnFunction() == 3
Run Code Online (Sandbox Code Playgroud)

或者您可以将其添加到单个实例中

    String a = "Tim"
    a.metaClass.myOwnFunction = {-> delegate.length() }
    assert a.myOwnFunction() == 3
Run Code Online (Sandbox Code Playgroud)

或者,当jar在启动时使用扩展模块在类路径中时,可以添加这些方法