Dart中的typedef是什么? [英] What is a typedef in Dart?
问题描述
我已经阅读了说明,并且我知道它是函数类型的别名。
I have read the description, and I understand that it is a function-type alias.
-
typedef,或者函数类型别名,为函数类型提供一个名称,您可以在声明字段和返回类型时使用该名称。在将函数类型分配给变量时,typedef会保留类型信息。
A typedef, or function-type alias, gives a function type a name that you can use when declaring fields and return types. A typedef retains type information when a function type is assigned to a variable.
http://www.dartlang.org/docs/spec/latest/dart-language-specification.html#kix.yyd520hand9j
但是我该如何使用呢?为什么用函数类型声明字段?什么时候使用?它解决什么问题?
But how do I use it? Why declaring fields with a function-type? When do I use it? What problem does it solve?
我想我需要一个或两个真实的代码示例。
I think i need one or two real code examples.
推荐答案
Dart中typedef的一种常见用法是定义一个回调接口。例如:
A common usage pattern of typedef in Dart is defining a callback interface. For example:
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');
}
运行上述示例将产生以下输出:
Running the above sample yields the following output:
Hello World
2012-09-22 10:19:15.139:Hello World
Hello World
2012-09-22 10:19:15.139: Hello World
typedef行表示LoggerOutputFunction接受String参数并返回void。
The typedef line says that LoggerOutputFunction takes a String parameter and returns void.
timestampLoggerOutputFunction与该定义匹配,因此可以分配给
timestampLoggerOutputFunction matches that definition and thus can be assigned to the out field.
让我知道您是否需要另一个示例。
Let me know if you need another example.
这篇关于Dart中的typedef是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!