在java - Why are only final variables accessible in anonymous class? - Stack Overflow中,Jon Skeet 说了这么一段话:
When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)
我对“This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does...”的理解是:如果要实现 full closures support,那么就需要产生一个共享的数据结构用来包含外部方法和内部类所共同访问的变量,这样两者都是使用同一个数据源,那么一方对变量的改变就会对另一方可见,类似Ivan Dubrov 所说的。
我不肯定我的理解是否正确,所以我想看一下大家对这句话的理解。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.