86

我已经阅读了描述,并且我理解它是一个函数类型的别名。

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

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

4

6 回答 6

106

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: 你好世界

typedef 行说 LoggerOutputFunction 接受一个字符串参数并返回 void。

timestampLoggerOutputFunction 与该定义匹配,因此可以分配给 out 字段。

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

于 2012-09-22T17:21:13.663 回答
29

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

于 2018-04-19T04:22:16.420 回答
20
typedef LoggerOutputFunction = void Function(String msg);

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

于 2019-05-05T23:49:31.430 回答
10

只是稍微修改了答案,根据最新的 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');
}
于 2019-04-26T02:00:41.213 回答
3

Typedef在 Dart 中用于为其他应用程序功能创建用户定义的函数(别名),

Syntax: typedef function_name (parameters);

在 typedef 的帮助下,我们还可以将变量分配给函数。

Syntax:typedef variable_name = function_name;

分配变量后,如果我们必须调用它,那么我们可以这样:

Syntax: variable_name(parameters);

例子:

// Defining alias name
typedef MainFunction(int a, int b);

functionOne(int a, int b) {
  print("This is FunctionOne");
  print("$a and $b are lucky numbers !!");
}

functionTwo(int a, int b) {
  print("This is FunctionTwo");
  print("$a + $b is equal to ${a + b}.");
}

// Main Function
void main() {
  // use alias
  MainFunction number = functionOne;

  number(1, 2);

  number = functionTwo;
 // Calling number
  number(3, 4);
}

输出:

This is FunctionOne
1 and 2 are lucky numbers !!
This is FunctionTwo
3 + 4 is equal to 7
于 2020-09-15T16:14:29.153 回答
2

从 dart 2.13 版开始,您typedef不仅可以使用函数,还可以使用您想要的每个对象。

例如,这段代码现在完全有效:

typedef IntList = List<int>;
IntList il = [1, 2, 3];

有关更多详细信息,请参阅更新信息: https ://dart.dev/guides/language/language-tour#typedefs

于 2021-05-20T20:18:52.193 回答