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

查看:108
本文介绍了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:

你好世界
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 中的函数类型定义/函数类型别名是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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