我已经阅读了描述,我知道它是一个函数类型的别名。
但是我该如何使用它?为什么用函数类型声明字段?我什么时候使用它?它解决了什么问题?
我想我需要一两个真正的代码示例。
Dart中typedef的常见用法模式是定义回调接口。例如:
typedef void LoggerOutputFunction(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
运行上面的示例会产生以下输出:
你好,世界 2012-09-22 10:19:15.139:Hello World
typedef行表示LoggerOutputFunction接受String参数并返回void。
timestampLoggerOutputFunction匹配该定义,因此可以分配给out字段。
如果您需要另一个例子,请告诉我。
Dart 1.24引入了一种新的typedef语法,以支持通用函数。仍支持以前的语法。
typedef F = List<T> Function<T>(T);
有关更多详细信息,请参阅https://github.com/dart-lang/sdk/blob/master/docs/language/informal/generic-function-type-alias.md
函数类型也可以内联指定
void foo<T, S>(T Function(int, S) aFunction) {...}
另见https://www.dartlang.org/guides/language/language-tour#typedefs
根据最新的typedef语法稍加修改的答案,该示例可以更新为:
typedef LoggerOutputFunction = void Function(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
typedef LoggerOutputFunction = void Function(String msg);
这看起来比以前的版本更清晰