我对dart的理解是,Function<T>()
是一个表示返回类型为T的函数的类型。因此,如果我想提供这样的函数作为回调:
T wrapper<T>(Function<T>() f){
return f();
}
。编译。
但是当调用包装器并提供具有某种返回类型的函数时,我得到:
int myF()=>123;
callWrapper(){
int i = wrapper(myF); <<< error with myF
}
error: The argument type 'int Function()' can't be assigned to the parameter type 'dynamic Function<T>()'. (argument_type_not_assignable at ....
我不明白。为什么类型检查器认为int Function()
与Function<T>()
不匹配?
也以同样的方式失败:
T wrapper<T>(T Function() f){ ///<<<<
return f();
}
int myF()=>123;
callWrapper(){
int i = wrapper(myF);
}
这里的问题是参数Function<T>() f
并不是说"f
一个不带参数并返回T
的Function
",它实际上是在说"f
是一个不带参数并返回dynamic
Function<T>
"。
有两种方法可以完成此操作:
1.
T wrapper<T>(T Function() f) { ... }
阿拉伯数字。
T wrapper<T>(T f()) { ... }
从dart:core
Function
类没有任何类型变量。我认为分析器应该警告你不要做Function<T>()
但事实并非如此。