在静态范围内访问全局变量 [英] access global variable in static scope
本文介绍了在静态范围内访问全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以从同一脚本中声明的类的静态方法访问脚本中声明的全局变量?
Is there a way to access global variable, declared in the script, from the static method of the class, declared in the same script?
例如
def s = "12345"
class MyClass {
static def method() {
println s
}
}
因为那样,它会因错误而失败
Because that way it fails with the error
You attempted to reference a variable in the binding or an instance variable from a static context
尽管如此.
推荐答案
此问题有相关讨论:
相关之处在于,这两个问题都涉及在类中使用全局变量,但是这个问题有所不同,因为您正在尝试使用静态方法来更改传递脚本实例或绑定的方式(2个选择).
Related in that both questions refer to using a global variable within a class, but this question differs somewhat in that you are seeking to use a static method which alters how you pass the script instance or binding (2 choices).
传递脚本实例
import groovy.transform.Field
@Field def s = "12345"
class MyClass {
static def method(si) {
return si.s
}
}
assert MyClass.method(this) == "12345"
传递脚本的绑定
s = "12345" // NOTE: no 'def'
class MyClass {
static def method(b) {
return b.s
}
}
assert MyClass.method(binding) == "12345"
这篇关于在静态范围内访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文