gpt4 book ai didi

groovy - 这个,所有者,Groovy 闭包中的委托(delegate)

转载 作者:行者123 更新时间:2023-12-01 07:10:23 33 4
gpt4 key购买 nike

这是我的代码:

class SpecialMeanings{
String prop1 = "prop1"
def closure = {
String prop1 = "inner_prop1"
println this.class.name //Prints the class name
println this.prop1
println owner.prop1
println delegate.prop1
}
}

def closure = new SpecialMeanings().closure
closure()

输出是
prop1
prop1
prop1

我希望第一行是 prop1 ,因为它指的是定义闭包的对象。但是,所有者(并且是默认委托(delegate)人)应该引用实际的闭包。所以接下来的两行应该是 inner_prop1。他们为什么不呢?

最佳答案

这就是它的工作原理。 owner的实际引用你要明白和 delegate . :)

class SpecialMeanings{
String prop1 = "prop1"
def closure = {
String prop1 = "inner_prop1"
println this.class.name //Prints the class name

//Refers to SpecialMeanings instance
println this.prop1 // 1

// owner indicates Owner of the surrounding closure which is SpecialMeaning
println owner.prop1 // 2

// delegate indicates the object on which the closure is invoked
// here Delegate of closure is SpecialMeaning
println delegate.prop1 // 3

// This is where prop1 from the closure itself in referred
println prop1 // 4
}
}

def closure = new SpecialMeanings().closure
closure()

//Example of modifying the delegate to the script itself
prop1 = "PROPERTY FROM SCRIPT"
closure.delegate = this
closure()

脚本的最后 3 行显示了如何更改默认委托(delegate)并将其设置为闭包的示例。上次调用 closure将打印 prop1脚本中的值 PROPERTY FROM SCRIPTprintln # 3

关于groovy - 这个,所有者,Groovy 闭包中的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23449376/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com