这是解释here。最重要的部分是:
每次创建闭包时,该闭包都是一个新对象。
您可以将对象存储在变量中以解决此问题。顶级函数和静态方法按您的预期工作。
void main() {
var foo = new Foo();
if (foo.someMethod == foo.someMethod)
print("foo.someMethod == foo.someMethod");
else
print("foo.someMethod != foo.someMethod");
var storedMethodClosure = foo.someMethod;
if (storedMethodClosure == storedMethodClosure)
print("storedMethodClosure == storedMethodClosure");
else
print("storedMethodClosure != storedMethodClosure");
if (someFunction == someFunction)
print("someFunction == someFunction");
else
print("someFunction != someFunction");
if (Foo.staticMethod == Foo.staticMethod)
print("Foo.staticMethod == Foo.staticMethod");
else
print("Foo.staticMethod != Foo.staticMethod");
}
void someFunction() {
}
class Foo {
someMethod() {
}
static staticMethod() {
}
}
这输出:
foo.someMethod != foo.someMethod
存储方法闭包 == 存储方法闭包
someFunction == someFunction
Foo.staticMethod == Foo.staticMethod