2
是否可以將Groovy關閉範圍設置爲調用方法?請參見下面的示例代碼:將關閉範圍設置爲調用方法
class TestClass {
def testMethod() {
def i = 42
def closure = testClosure()
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure.delegate = this.&testMethod
closure() // Should print 42.
}
def testMethod2() {
def i = 43
def closure = testClosure()
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure.delegate = this.&testMethod2
closure() // Should print 43.
}
def testClosure = {
println i // I get a MissingPropertyException: No such property i
}
}
def test = new TestClass()
test.testMethod()
test.testMethod2()
好的,謝謝,我很害怕,可能是這樣。我有兩個具有50%相同代碼和大量通用變量的Grails動作,並且希望有一個簡單的解決方案來統一兩者,而無需將所有變量傳遞給一個通用函數(即使用通用閉包,而不是已經可以訪問所有變量變量)。但除此之外,這是不可行的,它可能是醜陋的,以及; - ) – wwwclaes