1

在 Gradle 脚本中,我有一个带有委托的 Groovy 闭包,并且我在该委托上创建了一个函数调用方法,如下所述:

// Simplified example
ant.compressFiles() {
    addFile(file: "A.txt")
    addFile(file: "B.txt")
    addAllFilesMatching("C*.txt", getDelegate())
}

def addAllFilesMatching(pattern, closureDelegate) {
    // ...
    foundFiles.each {
        closureDelegate.addFile(file: it)
    }
}

是否有可能以更漂亮的方式做到这一点,而不必将委托传递给函数?例如,是否可以使用新方法以某种方式扩展委托?

4

3 回答 3

1

这可以通过创建一个返回 a 的函数来解决Closure

ant.compressFiles() addAllFilesMatching("A.txt", "B.txt", "C*.txt")

Closure addAllFilesMatching(String... patterns) {
    // Calculate foundFiles from patterns...
    return {
        foundFiles.each { foundFile ->
            addFile(file: foundFile)
        }
    }
}
于 2016-02-10T12:34:14.117 回答
0

您可以先声明闭包,设置其delegateresolveStrategy然后将其传递给each

def addAllFilesMatching(pattern, delegate) {

  def closure = {
    addFile file: it
  }

  closure.delegate = delegate
  closure.resolveStrategy = Closure.DELEGATE_FIRST

  foundFiles = ["a.txt", "b.txt", "c.txt", "d.txt"]

  foundFiles.each closure
}
于 2013-07-16T16:30:15.857 回答
0

这个怎么样?

这是对 WillP 答案的微小修改(这是绝对正确的,应该这样做)并且应该更漂亮(根据您的要求),因为它使用闭包而不是方法。

def addAllFilesMatching = {pattern ->
    // ... foundFiles based on pattern
    foundFiles.each {
        delegate.addFile(file: it)
    }
}

ant.compressFiles() {
    addFile(file: "A.txt")
    addFile(file: "B.txt")

    addAllFilesMatching.delegate = getDelegate() 
    addAllFilesMatching("C*.txt")
}
于 2013-07-16T16:54:46.877 回答