我了解到,默认情况下,委派首先与所有者合作,否则需要特定的委派。我不明白嵌套闭包委托的工作方式。 我的例子:
class App1 {
String bar = "App1"
}
class App2 {
Closure c1 = {
String bar = "App2"
println("Closure 1 - $bar")
Closure c2 = {
println("Closure2 - $bar")
}
c2.delegate = new App1()
c2.resolveStrategy = Closure.DELEGATE_ONLY
c2()
}
}
App2 app2 = new App2()
App1 app1 = new App1()
app2.c1.delegate = app1
app2.c1()
println("***************")
app2.c1.resolveStrategy = Closure.DELEGATE_ONLY // Delegation strictly to
app2.c1()
喜欢是结果
Closure 1 - App2
Closure2 - App2
***************
Closure 1 - App2
Closure2 - App2
对我来说没有意义的是最后一行。即使在使用DELEGATE_ONLY将Closure c2委派给App1之后,为什么还要考虑bar =“ App2”?!
答案 0 :(得分:1)
它选择bar
作为局部变量bar
,它根本不需要看委托来解决它,所以一切都是App2
如果将其移至app2中的闭包之外:
class App2 {
String bar = "App2"
Closure c1 = {
println("Closure 1 - $bar")
Closure c2 = {
println("Closure2 - $bar")
}
c2.delegate = new App1()
c2.resolveStrategy = Closure.DELEGATE_ONLY
c2()
}
}
您得到了输出
Closure 1 - App2
Closure2 - App1
***************
Closure 1 - App1
Closure2 - App1