是否可以将 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()
最佳答案
不,但您可以将 i
移动到与闭包相同的范围:
class TestClass {
def i
def testMethod() {
i = 42
testClosure() // Should print 42.
}
def testMethod2() {
i = 43
testClosure() // Should print 43.
}
def testClosure = {
println i // I get a MissingPropertyException: No such property i
}
}
def test = new TestClass()
test.testMethod()
test.testMethod2()
关于groovy - 将闭包范围设置为调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32987623/