首页 > 解决方案 > 如何创建类似 C# 的扩展方法

问题描述

我想将公共方法附加到类。这在 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

标签: groovy

解决方案


你会想要这样的东西:

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


推荐阅读