Dart中的函数typedefs/函数类型别名是什么? [英] What are function typedefs / function-type aliases in Dart?

查看:77
本文介绍了Dart中的函数typedefs/函数类型别名是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了说明,并且我知道它是函数类型的别名.

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
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与该定义匹配,因此可以分配给out字段.

timestampLoggerOutputFunction matches that definition and thus can be assigned to the out field.

如果您需要其他示例,请告诉我.

Let me know if you need another example.

这篇关于Dart中的函数typedefs/函数类型别名是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆