现在有两种在Dart中使用typedef的方法吗? [英] Are there now two ways to use typedef in Dart?

查看:121
本文介绍了现在有两种在Dart中使用typedef的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在整个飞镖库和Flutter库中看到了多种形式的 typedef ,但是我不太理解。在frame.dart中有以下示例:

I see multiple forms of typedef throughout dart and flutter libraries, but I can't quite make sense of it. There's this example in framework.dart:

typedef ElementVisitor = void Function(Element element);

有一个示例( https://medium.com/@castellano.mariano/typedef-in-dart-40e96d3941f9 ):

typedef String Join(String a, String b);

我不太了解它们的用途。也许这与为什么我找不到功能的定义有关。 Dart或Flutter库中的任何位置。但是再一次,我可以在framework.dart文件中找到其他typedef就可以了。

I don't quite understand the difference of their uses. Maybe this has something to do with why I can't find the definition of "Function" anywhere in the Dart or Flutter libraries. But then again I can find other typedef's just fine in the framework.dart file.

推荐答案

文档引用

通常有一种新的 typedef

方式:新方式更清晰,

in general: the new way is a bit clearer and more readable.

详细信息:

typedef G = List<int> Function(int); // New form.
typedef List<int> H(int i); // Old form.



请注意,参数名称是旧格式的必填项,但是类型可能是被省略。相反,在新表格中必须输入类型,但可以省略名称。

Note that the name of the parameter is required in the old form, but the type may be omitted. In contrast, the type is required in the new form, but the name may be omitted.

以及

使用两种方式表示同一件事的原因是,新表单无缝地覆盖了非泛型函数和泛型函数,并且开发人员可能更喜欢在各处使用新表单以进行改进可读性。

The reason for having two ways to express the same thing is that the new form seamlessly covers non-generic functions as well as generic ones, and developers might prefer to use the new form everywhere, for improved readability.



在声明泛型函数类型与声明带有类型参数的typedef之间存在区别。前者是一种单一类型的声明,描述了某些类型的运行时实体:能够在运行时接受某些类型参数和某些值参数的函数。后者是从类型到类型的编译时映射:它在编译时接受类型实参,并返回一个类型,该类型可以用作类型注释。我们使用短语参数化typedef来指代后者。 Dart支持参数​​化typedef已有一段时间了,新语法也支持参数化typedef。这是参数化typedef及其用法的示例:

There is a difference between declaring a generic function type and declaring a typedef which takes a type argument. The former is a declaration of a single type which describes a certain class of runtime entities: Functions that are capable of accepting some type arguments as well as some value arguments, both at runtime. The latter is a compile-time mapping from types to types: It accepts a type argument at compile time and returns a type, which may be used, say, as a type annotation. We use the phrase parameterized typedef to refer to the latter. Dart has had support for parameterized typedefs for a while, and the new syntax supports parameterized typedefs as well. Here is an example of a parameterized typedef, and a usage thereof:


typedef I<T> = List<T> Function(T); // New form.
typedef List<T> J<T>(T t); // Old form.
I<int> myFunction(J<int> f) => f;

更多信息

这篇关于现在有两种在Dart中使用typedef的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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