Как создать метод расширения как C # - PullRequest
0 голосов
/ 28 сентября 2018

Я хочу прикрепить публичный метод к классу.Это называется метод расширения в 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 голосов
/ 28 сентября 2018

Вам понадобится что-то вроде этого:

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 для получения дополнительной информации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...