Dart中的typedef是什么?

问题描述 投票:43回答:4

我已经阅读了描述,我知道它是一个函数类型的别名。

但是我该如何使用它?为什么用函数类型声明字段?我什么时候使用它?它解决了什么问题?

我想我需要一两个真正的代码示例。

typedef dart
4个回答
60
投票

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字段。

如果您需要另一个例子,请告诉我。


15
投票

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


0
投票

根据最新的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');
}

0
投票
typedef LoggerOutputFunction = void Function(String msg);

这看起来比以前的版本更清晰

© www.soinside.com 2019 - 2024. All rights reserved.