方法指针和对象引用 [英] method pointer and object reference
问题描述
在这个例子中
类累加器{
def count = 0
def accumulate(){
print(++ count)
def ac_inst = new累加器()
3.times {
ac_inst.accumulate()// 123
}
def accum = ac_inst。& accumulate
ac_inst = 5 //改变参考
8.times {
accum()// 4567891011
}
我使用方法<$ c $创建了闭包 accum
c> accumulate of ac_inst
object - MyClass
的实例。
我将 ac_inst
值更改为完全不同的对象,但闭包调用继续增加 count
值,尽管没有 ac_inst
对象。
它在那里存储了该闭包的所需值?
闭包有一个委托
(可以修改)和一个所有者
(严格地说不能)
所以它涉及的实例存储在这里,改变它原来的价值不会改变它。
事实上,我可以想到的几乎每一种语言都是这样:
def list = [1,2,3]
def val = list [1]
list = [4,5,6]
println val // still 2
Where Groovy stores the reference to the variables used inside class method, which I transformed into closure.
In this example
class Accumulator {
def count = 0
def accumulate() {
print (++count)
}
}
def ac_inst= new Accumulator()
3.times {
ac_inst.accumulate() //123
}
def accum = ac_inst.&accumulate
ac_inst = 5 // changed reference
8.times {
accum() //4567891011
}
I created closure accum
using method accumulate
of ac_inst
object - instance of MyClass
.
The I changed ac_inst
value to completely different object, but closure invokation continued to increment count
value despite not having ac_inst
object anymore.
Where it stores the required values for that closure?
A closure has a delegate
(which may be modified) and an owner
(which strickly speaking can not)
So the instance it relates to is stored in here, and just changing the value it was originally from isn't going to change it.
Indeed this is true of pretty much every part of the language I can think of:
def list = [1,2,3]
def val = list[1]
list = [4,5,6]
println val // still 2
这篇关于方法指针和对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!