如何创建像C#这样的扩展方法

时间:2018-09-28 17:26:42

标签: groovy

我想在类上附加公共方法。 这称为extension method in C#

package extensionMethods

class A {

    def testA() {}

    //def testB() {} Need to add a public method to this class A but we don't have access to the class

}

class B {

    def test() {

        def a = new A();
        a.testA()

        a.testB() //Need to add a public method to the Class A without defining the method in the class A
    }
}

//In C# way -> Extension method
class C {

   /* void testB(this A a) {
    }*/

}

我们如何在Groovy中实现类似的方法? 在上面的示例中,我想将方法​​testB()附加到class A

1 个答案:

答案 0 :(得分:0)

您将想要这样的东西:

package something

class SomeExtensionClass {
    static void testB(A self) {
        // ...
    }
}

然后您的META-INF/services/org.codehaus.groovy.runtime.ExtensionModule扩展描述符...

moduleName=Test module for specifications
moduleVersion=1.0-test
extensionClasses=something.SomeExtensionClass

有关更多信息,请参见http://groovy-lang.org/metaprogramming.html#_extension_modules

相关问题