将带有参数的函数传递给VoidCallback [英] Pass a function with parameters to a VoidCallback
问题描述
是否可以将带有参数的函数传递给VoidCallback?
Is it possible to pass a Function with parameters to a VoidCallback?
例如这样的东西:
class MyClass {
void doSomething(int i){
}
MyOtherClass myOtherClass = new MyOtherClass(doSomething);
}
class MyOtherClass {
final VoidCallback callback(int);
MyOtherClass(this.callback);
callback(5);
}
推荐答案
<$ c的声明$ c> VoidCallback 是
typedef void VoidCallback();
这是可以使用零参数调用并且不返回有用值的函数类型。那似乎不是您想要的。
由于该程序在语法上无效,因此尚不完全清楚您想要的是什么,但这对您有用吗?
That is the type of functions that can be called with zero arguments and which does not return a useful value. That does not seem to be what you want. It's not entirely clear what you do want since the program isn't syntactically valid, but would this work for you:
class MyClass {
static doSomething(int i) { /* ... */ }
MyOtherClass myOtherClass = new MyOtherClass(doSomething);
}
class MyOtherClass {
final void Function(int) callback;
MyOtherClass(this.callback);
void callCallaback() { callback(5); }
}
在此,我们定义回调的类型
字段是可以使用一个整数参数调用且不返回任何有用值的函数的类型。 doSomething
方法具有该类型,因此可以将其分配给 callback
。
Here we define the type of the callback
field to be the type of functions that can be called with one integer argument and which returns no useful value. The doSomething
method has that type, so it can be assigned to callback
.
您也可以使用typedef来命名函数:
You could also use a typedef to name the function:
typedef Int2VoidFunc = void Function(int);
// or: typedef void Int2VoidFunc(int arg);
class MyOtherClass {
final Int2VoidFunc callback;
MyOtherClass(this.callback);
void callCallaback() { callback(5); }
}
效果是完全一样的,只是允许您使用较短的函数类型的名称,但是只有经常使用它才有意义。
The effect is exactly the same, it just allows you to use a shorter name for the function type, but that only really makes sense if you use it a lot.
这篇关于将带有参数的函数传递给VoidCallback的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!